List(1,2) match {
case List(1,_) => println("1 in postion 1")
case _ => println("default")
}
Run Code Online (Sandbox Code Playgroud)
编译/工作正常.那样做
List(1) match ...
List(3,4,5) match ...
Run Code Online (Sandbox Code Playgroud)
但不是
List() match ...
Run Code Online (Sandbox Code Playgroud)
这会导致以下错误
found : Int(1)
required : Nothing
case List(1,_) => println("1 in postion 1")
Run Code Online (Sandbox Code Playgroud)
为什么List()尝试匹配List(1,_)?
Rex*_*err 12
List()有类型List[Nothing].如果您使用List[Int]()它将按预期工作.
(通常,类型尽可能具有限制性;因为您已经创建了一个没有任何内容的列表,所以使用了最具限制性的类型Nothing而不是Int您想要的类型.)
在您编写时List(),推断的类型是Nothing,这是所有内容的子类型.
发生的事情是当您尝试不可能的匹配时Scala会出错.例如,"abc" match { case 1 => }将导致类似的错误.同样,因为List(1, _)可以静态地确定永不匹配List(),Scala会给出错误.