我试图匹配 Seq
的情况包含 Nothing
.
models.Tasks.myTasks(idUser.toInt) match {
case tasks => tasks.map {
task => /* code here */
}
case _ => "" //matches Seq(models.Tasks)
}
怎么样
Seq[Nothing]
用模式匹配表示?
最佳答案
与空序列匹配如下所示:
val x: Seq[Nothing] = Vector()
x match {
case Seq() => println("empty sequence")
}
编辑:请注意,这比
case Nil
更通用自 Nil
仅是 List
的子类,不是 Seq
一般来说。奇怪的是,编译器可以匹配 Nil
如果类型被显式注释为 Seq
, 但如果类型是任何非 List
,它会提示Seq
的子类.因此你可以这样做:(Vector(): Seq[Int]) match { case Nil => "match" case _ => "no" }
但不是这个(因编译时错误而失败):
Vector() match { case Nil => "match" case _ => "no" }
关于Scala:模式匹配 Seq[Nothing],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13068080/