我试图匹配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