2010-08-27 104 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