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.
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).
ReplyDeleteI 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.
ReplyDeleteConsider 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?