Scala:模式匹配Seq [Nothing]

时间:2012-10-25 11:58:53

标签: scala

我正在尝试匹配Seq包含Nothing的情况。

models.Tasks.myTasks(idUser.toInt) match {
  case tasks => tasks.map {
    task => /* code here */
  }
  case _ => "" //matches Seq(models.Tasks)
}

Seq[Nothing]如何在模式匹配中表示?

2 个答案:

答案 0 :(得分:11)

匹配空序列如下所示:

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" }

答案 1 :(得分:9)

假设我理解你的意思正确,包含任何内容的序列都是空的,即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是正确的,如果你手动创建一个特定的子类型,例如vector,那么匹配不起作用:

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"} 

话虽如此,我不知道为什么你需要强迫你的对象经常被称为特定的具体子类。

相关问题