tags:

views:

106

answers:

3
+3  Q: 

scala list match

List(1,2) match {
  case 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,_)?

+2  A: 

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]]
missingfaktor
What this means is that `List[Int]` is coercible to `List[Nothing]` but the other way round is not possible.
missingfaktor
+8  A: 

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

Rex Kerr
+5  A: 

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.

Daniel