Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala list match

Tags:

list

match

scala

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,_)?

like image 252
Dave.Sol Avatar asked Aug 27 '10 15:08

Dave.Sol


1 Answers

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

like image 84
Rex Kerr Avatar answered Oct 13 '22 20:10

Rex Kerr