Scala列表匹配

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

为什么List()会尝试匹配List(1,_)?
3个回答

12

List()的类型为List[Nothing]。如果您使用List[Int](),它将按您预期工作。

一般而言,类型限制尽可能严格;因为您创建了一个什么都没有的列表,所以使用了最严格的类型Nothing,而不是您本来想用的Int


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接