2010-08-27 230 views
6
List(1,2) match { 
    case List(1,_) => println("1 in postion 1") 
    case _ => println("default") 
} 

編譯/工作正常。 所以做斯卡拉列表匹配

List(1) match ... 
List(3,4,5) match ... 

但不

List() match ... 

這將導致以下錯誤

found : Int(1) 
required : Nothing 
      case List(1,_) => println("1 in postion 1") 

爲什麼列表()嘗試匹配列表(1,_)?

回答

6

當你寫List()時,推斷的類型是Nothing,它是所有事物的子類型。

發生了什麼事情是,當你嘗試不可能的匹配時,Scala會給出錯誤。例如,"abc" match { case 1 => }將導致類似的錯誤。同樣,因爲List(1, _)可以靜態確定從不匹配List(),Scala會給出錯誤。

2

也許是因爲......

scala> implicitly[List[Nothing] <:< List[Int]] 
res3: <:<[List[Nothing],List[Int]] = <function1> 

scala> implicitly[List[Int] <:< List[Nothing]] 
<console>:6: error: could not find implicit value for parameter e:<:<[List[Int],List[Nothing]] 
     implicitly[List[Int] <:< List[Nothing]] 
+4

這是什麼意思是'List [Int]'可以強制爲'List [Nothing]',但其他方式是不可能的。 – missingfaktor 2010-08-27 15:53:38

12

List()具有類型List[Nothing]。如果您使用List[Int](),它將按照您的預期工作。

(一般來說,類型有限制,因爲他們都不可能。因爲你已經什麼也沒有在它的列表,你想要的最嚴格的,可能的類型Nothing代替Int