The problem is that Scala starts type inference with the first parameter list. So given def foldLeft[B](z: B)(f: (B, A) => B): B
and
xs.foldLeft(Nil)(...)
it infers B
as Nil.type
(type which has only one value: Nil
) and uses this to type-check the second parameter list, which obviously fails. However, List[String]()
has the type List[String]
and so B
is List[String]
, which will work with your f
. Another workaround is to write the type parameter explicitly:
xs.foldLeft[List[String]](Nil)(...)
In the second program, type of acc
is given (and has to be, since it's a function argument), so no type inference happens corresponding to your initial problem.