2012-10-25 408 views
1

我試圖匹配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]如何在模式匹配中表示?

回答

6

假設我理解你正確的意思,沒有包含任何序列是空的,這是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"} 

話雖如此,我不知道你爲什麼會需要你的力量對象經常被稱爲特定的具體子類。

+0

說'SEQ()''調用列表()'後面,因爲'Seq'幕後是一個接口。然而,'List'不是'Seq'的唯一實現,只是默認的一個。嘗試使用*任何其他種類的'Seq',它會失敗。 – dhg

+0

@dhg'(Vector():Seq [Int])match {case Nil =>「match」case _ =>「no」}'returns「match」 –

+0

@Luigi,'Vector()match {case Nil = >「match」case _ =>「no」}'不。我發現這種錯配很奇怪。 – dhg

9

匹配對空序列如下:

val x: Seq[Nothing] = Vector() 

x match { 
    case Seq() => println("empty sequence") 
} 

編輯:請注意,這是更普遍比自Nilcase Nil是一個子類只有List,一般不Seq。奇怪的是,如果類型明確標註爲Seq,編譯器可以與Nil進行匹配,但是如果該類型是Seq的任何非List子類,它將會投訴。因此,你可以這樣做:

(Vector(): Seq[Int]) match { case Nil => "match" case _ => "no" } 

但不是這個(失敗,編譯時錯誤):

Vector() match { case Nil => "match" case _ => "no" } 
+0

那就更好地刪除我的答案吧! – Russell

+0

我剛剛在控制檯中測試了這個,我認爲它會起作用 – Russell

+0

已經在我的答案中添加了一些repl輸出以顯示此操作。 – Russell