我試圖匹配Seq
包含Nothing
的情況。Scala:模式匹配Seq [Nothing]
models.Tasks.myTasks(idUser.toInt) match {
case tasks => tasks.map {
task => /* code here */
}
case _ => "" //matches Seq(models.Tasks)
}
Seq[Nothing]
如何在模式匹配中表示?
我試圖匹配Seq
包含Nothing
的情況。Scala:模式匹配Seq [Nothing]
models.Tasks.myTasks(idUser.toInt) match {
case tasks => tasks.map {
task => /* code here */
}
case _ => "" //matches Seq(models.Tasks)
}
Seq[Nothing]
如何在模式匹配中表示?
假設我理解你正確的意思,沒有包含任何序列是空的,這是Nil
:
case Nil => //do thing for empty seq
這個工程即使你正在處理Seq
S,不Lists
:
scala> Seq()
res0: Seq[Nothing] = List()
scala> Seq() == Nil
res1: Boolean = true
一些更多的REPL輸出顯示,這與其他小類Seq
絕對正常:
scala> Nil
res3: scala.collection.immutable.Nil.type = List()
scala> val x: Seq[Int] = Vector()
x: Seq[Int] = Vector()
scala> x == Nil
res4: Boolean = true
scala> x match { case Nil => "it's nil" }
res5: java.lang.String = it's nil
scala> val x: Seq[Int] = Vector(1)
x: Seq[Int] = Vector(1)
scala> x match { case Nil => "it's nil"; case _ => "it's not nil" }
res6: java.lang.String = it's not nil
從上面的輸出可以看出,Nil
是一種屬於它自己的類型。這個question有關於此事的一些有趣的事情要說。
但@dhg是正確的,如果您手動創建一個特定的亞型,如向量,這場比賽不工作:
scala> val x = Vector()
x: scala.collection.immutable.Vector[Nothing] = Vector()
scala> x match { case Nil => "yes"}
<console>:9: error: pattern type is incompatible with expected type;
found : object Nil
required: scala.collection.immutable.Vector[Nothing]
x match { case Nil => "yes"}
話雖如此,我不知道你爲什麼會需要你的力量對象經常被稱爲特定的具體子類。
匹配對空序列如下:
val x: Seq[Nothing] = Vector()
x match {
case Seq() => println("empty sequence")
}
編輯:請注意,這是更普遍比自Nil
case Nil
是一個子類只有List
,一般不Seq
。奇怪的是,如果類型明確標註爲Seq
,編譯器可以與Nil
進行匹配,但是如果該類型是Seq
的任何非List
子類,它將會投訴。因此,你可以這樣做:
(Vector(): Seq[Int]) match { case Nil => "match" case _ => "no" }
但不是這個(失敗,編譯時錯誤):
Vector() match { case Nil => "match" case _ => "no" }
說'SEQ()''調用列表()'後面,因爲'Seq'幕後是一個接口。然而,'List'不是'Seq'的唯一實現,只是默認的一個。嘗試使用*任何其他種類的'Seq',它會失敗。 – dhg
@dhg'(Vector():Seq [Int])match {case Nil =>「match」case _ =>「no」}'returns「match」 –
@Luigi,'Vector()match {case Nil = >「match」case _ =>「no」}'不。我發現這種錯配很奇怪。 – dhg