Scala matching list
List(1,2) match { case List(1,_) => println("1 in postion 1") case _ => println("default") } compiles / works fine. So that
List(1) match ... List(3,4,5) match ... but not
List() match ... leading to the following error
found : Int(1) required : Nothing case List(1,_) => println("1 in postion 1") Why is List () trying to match List (1, _)?
When you write List() , the type is deduced by Nothing , which is a subtype of everything.
What happens is that Scala gives an error when trying to make impossible matches. For example, "abc" match { case 1 => } will result in a similar error. Similarly, since List(1, _) can be statically defined to never match List() , Scala gives an error.
List() is of type List[Nothing] . If you use List[Int]() , it will work as you expect.
(In general, types are as restrictive as possible, since you created a list that has nothing, instead of Int use the most restrictive type Nothing , as you expected.)
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]]