Sunday, September 20, 2009

Missing Parameter Type For Expanded Function?

I just made a silly Scala syntax mistake and got a fairly unhelpful compiler error message (often the case with newer languages). Google wasn't much help, so I thought I should post up the solution to help others save time in the future.

The code I wrote was essentially this:

def main(args: Array[String]) {
println(for {s <- List("One", "Two", "Three")} yield _) }

And the error I got was this:

error: missing parameter type for expanded function ((x$1) => List("One", "Two", "Three").map(((s) => x$1)))
println(for {s <- List("One", "Two", "Three")} yield _)

My novice mistake was in assuming that I could use an underscore to access the variable from the 'for' comprehension. Simply changing that underscore to 's' fixed it good:

def main(args: Array[String]) {
println(for {s <- List("One", "Two", "Three")} yield s) }

Something else worth noting is that the command-line scalac was actually much more helpful than my IDE, because it printed a third line with a caret pointing straight at the underscore, while the IDE only told me what line the error was on.


  1. I'm coding scala since some time now and also read a bit about that. I can tell you that i would personally avoid the underscore as much as possible, why? There was a thread on the mailing list about all the different meanings of the underscore, it's just too many (IMHO).

  2. I can see how avoiding it is probably a good idea in many situations - it is a character that tends to disappear amongst everything else going on. However, in simple scenarios it can really cut down the amount of code required.

    Consider this for example:

    List("one", "two").map {"and " + _}

    without using underscore would become this:

    List("one", "two").map((s:String) => {"and " + s})

    It's a fair bit uglier, yeah?