1

Scala code:

val value = Some("100")
value.foreach( println(_.toInt) )   // !!! can't be compiled

The error message is:

missing parameter type for expanded function ((x$1)=>x$1.toInt)

Why it can't be compiled?

PS: And the following code is valid:

value.foreach( _.toInt )
value.foreach( x => println(x.toInt) )
Freewind
  • 193,756
  • 157
  • 432
  • 708

1 Answers1

4

The compiler message is a bit misleading, but it provides you with a hint: it tells you that it interpreted _.toInt as (x$1)=>x$1.toInt. So, putting it in place, you get

value.foreach( println( (x$1)=>x$1.toInt ) )

which is obviously not what you intended.

Here's IMO the cleanest way to solve your issue:

value.map( _.toInt ).foreach( println )
Nikita Volkov
  • 42,792
  • 11
  • 94
  • 169
  • Very useful answer. A small question, why scala won't treat `println(_.toInt)` a whole expression, and expand it to `(x) => println(x.toInt)`. What's the rule? – Freewind May 19 '13 at 12:18
  • 2
    @Freewind As you can see, there is an ambiguity of whether to resolve `.foreach(println(_.toInt))` as `.foreach(x => println(x.toInt))` or as `.foreach(println(x => x.toInt))`. Since Scala compiler doesn't do much of reverse analysis, it just chooses the most simple resolution, which is the closest scope. – Nikita Volkov May 19 '13 at 12:25
  • It's not a case of the compiler not doing enough analysis: the language spec is very clear, and you illustrate the kind of ambiguity that *would* arise if the spec were changed to make Freewind's example do what he thought it would! – Luigi Plinge May 19 '13 at 14:14
  • 2
    @LuigiPlinge Probably you didn't get me right. I didn't say anything about the spec, I just explained how the compiler makes its decision. Concerning the "clearness" of the spec, I would argue that. Freewind's expectations for `.foreach( println(_.toInt) )` are quite justified by how `.foreach( println(_) )` gets interpreted. To me this incoherent behaviour is an example of some bad design decisions adding unnecessary complexity to the language. – Nikita Volkov May 19 '13 at 16:49