scala list match
List(1,2) match {
case开发者_C百科 List(1,_) => println("1 in postion 1")
case _ => println("default")
}
compiles / works fine. So do
List(1) match ...
List(3,4,5) match ...
but not
List() match ...
which results in the following error
found : Int(1)
required : Nothing
case List(1,_) => println("1 in postion 1")
Why does List() try to match List(1,_)?
List() has type List[Nothing]. If you use List[Int]() it will work as you expect.
(In general, types are as restrictive as they can possibly be; since you have made a list with nothing in it, the most-restrictive-possible type Nothing is used instead of Int as you intended.)
When you write List(), the type inferred is Nothing, which is subtype to everything.
What is happening is that Scala gives an error when you try impossible matches. For example, "abc" match { case 1 => } will result in a similar error. Likewise, because List(1, _) can be statically determined to never match List(), Scala gives an error.
Maybe because...
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]]
加载中,请稍侯......
精彩评论