When I build a list using foldLeft I often get annoyed at having to explicitly type the injected parameter and wish I could just use `Nil’ instead – here’s a contrived example:
scala> List(1,2,3).foldLeft(List[Int]())((x,y) => y :: x)
res17: List[Int] = List(3, 2, 1)
scala> List(1,2,3).foldLeft(Nil)((x, y) => y :: x)
<console>:10: error: type mismatch;
found : List[Int]
required: scala.collection.immutable.Nil.type
List(1,2,3).foldLeft(Nil)((x,y) => y :: x)
This isn’t so bad with a List[Int] but as soon as you start using lists of your own classes, which are almost certainly going to have longer names, or even lists of tuples or other containers, so there are multiple class names you need to specify, it gets horrendous:
list.foldLeft(List.empty[(SomethingClass, SomethingElseClass)]) { (x,y) => y :: x }
I’m guessing that the reason it doesn’t work is that whereas with something like 5 :: Nil the compiler can infer the type of the empty list to be List[Int], but when Nil is passed as a parameter to foldLeft it doesn’t have enough information to do so, and by the time it gets round to being used its type is set. But – is it really true that it couldn’t? Could it not infer the type from the return type of the function passed as the second argument?
And if not, is there some neater idiom I just don’t know about?
Scalas type inference engine works from left to right – therefore scalac can not infer the correct type for the first parameter list of foldLeft. You have to give the compiler a hint what type to use. Instead of using
List[TYPE]()you can useList.empty[TYPE]: