0

Why does the following work only using the format a => xxx to define a function?

Some("Help").foreach(p => println(p + " me"))

will produce the output "Help me", which is what I expect. On the other hand, the following code (which I see as equivalent)

Some("Help").foreach(println(_ + " me"))

results in an error at the underscore: missing parameter type for expanded function ((x$1: ) => x$1.$plus(" me")).

But the following (very similar)

Some("Help").foreach(println(_))

results in "Help" which is also the expected behavior.

In a 3rd attempt, I tried to specify the type, like this:

Some("Help").foreach(println((_: String) + " me"))

and the result was error: type mismatch; found : Unit; required: String => ?

So, what is going on? Why doesn't the underscore syntax work?

DDRider62
  • 753
  • 6
  • 17
  • I edited the question to indicate how this is NOT a duplicate of the question you refer it to. They are 2 different questions. One is about why some syntax is not working. The other is about showing generic uses of the same type of syntax. – DDRider62 Jun 25 '17 at 17:39
  • I think scala turns the `_` into a partially applied function and then feeds the context to it so the second and forth cases can't be converted and thats why they fail – 0x6C38 Jun 25 '17 at 17:50
  • Thanks, Mr. D. I think I understand the difference now, and it is indeed a duplicate question as Yuval pointed out. I'm new to scala. When I use "println( _ )" the underscore is parameter substitution. But when I say "println(_ + " me")" it's no longer parameter substitution. The expression _ + "me" is now the definition of a function. – DDRider62 Jun 25 '17 at 18:08

0 Answers0