List("This","is","Scala").foreach(a => print(a+" "))
compiles fine, but
List("This","is","Scala").foreach(print(_+" "))
fails complaining of missing parameter type. I couldn’t figure out why it fails.
EDIT: I meant print not println – not that it makes logical difference.
The problem is that this
is not equivalent to
but to
Now, let’s see the type signature of
foreach:where
Ais the type parameter of theListitself. Since we have aList[String], the compiler knows one has to pass toforeachaFunction[String, B].In
a => print(a+" ")the type ofais already known then:String.In
print(a => a+" ")there is a problem, asprintis not aFunction. However, the compiler hasn’t considered that yet — it’s still trying to compilea => a+" ". So let’s look at the type ofPredef.print:So
a => a+" "must be of typeAny, which, of course, means it can be anything. It doesn’t help the compiler in asserting what the type ofais. Which doesn’t really matter, because you didn’t want to print aFunctionin first place.