2011-02-28 79 views
9

我一直在用脫水機玩弄最近,想知道清單提取是如何工作特別是這樣的:理解模式匹配的列表

List(1, 2, 3) match { 
    case x :: y :: z :: Nil => x + y + z // case ::(x, ::(y, ::(z , Nil))) 
} 

好::在模式被使用,所以我想,編譯器現在在:: - Object中查找unapply方法。所以試過這個:

scala> (::).unapply(::(1, ::(2, Nil))) 
res3: Option[(Int, List[Int])] = Some((1,List(2))) 

很好的工作。然而,這並不:

scala> (::).unapply(List(1,2,3))  
<console>:6: error: type mismatch; 
found : List[Int] 
required: scala.collection.immutable.::[?] 
     (::).unapply(List(1,2,3)) 

而這樣做:

scala> List.unapplySeq(List(1,2,3)) 
res5: Some[List[Int]] = Some(List(1, 2, 3)) 

其實我在那一刻有點摸不着頭腦。編譯器如何在這裏選擇不適用的正確實現。

回答

9

比賽,基本上是做如下:

(::).unapply(List[Int](1,2,3).asInstanceOf[::[Int]]) 

一旦它知道它是安全的(因爲List(1,2,3).isInstanceOf[::[Int]]true)。

+0

而編譯器試圖這樣做是因爲::是List的子類型?更新:我認爲我得到它^^。 – raichoo 2011-02-28 20:48:59

+1

@raichoo - 它會嘗試它,因爲你在模式中要求'::'。 – 2011-02-28 20:52:13

+0

是的,雖然如此。感謝澄清:) – raichoo 2011-02-28 20:55:08