2

In scala REPL, this works well

scala> (1 to 3).foreach(i => print(i + ","))
1,2,3,

But this won't work

scala> (1 to 3).foreach(print(_ + ","))
<console>:8: error: missing parameter type for expanded function ((x$1) => x$1.$plus(","))
              (1 to 3).foreach(print(_ + ","))

If I remove the +"," part, it works again:

scala> (1 to 3).foreach(print(_ ))
123

I think the (1 to 3).foreach(print(_ + ",")) might work because there is only one parameter, which is _. Why does scala complain about this?

Hanfei Sun
  • 45,281
  • 39
  • 129
  • 237
  • 3
    Because it expands to `(1 to 3).foreach(print(x => x + ","))` which is illegal – serejja Nov 25 '14 at 09:57
  • @serejja Thanks! But why does `(1 to 3).foreach(print(_ ))` work? Won't it expand to `(1 to 3).foreach(print(x => x ))`, which is also illegal? – Hanfei Sun Nov 25 '14 at 10:00
  • please see this answer http://stackoverflow.com/questions/1025181/hidden-features-of-scala/1083523#1083523 In short, `(1 to 3).foreach(print(_ + ","))` translates to the thing I wrote above, and `(1 to 3).foreach(print(_))` translates into `(1 to 3).foreach(x => print(x))` – serejja Nov 25 '14 at 10:05

1 Answers1

4
(1 to 3).foreach(print(_ + ","))

expands to

(1 to 3).foreach(print(x => x + ","))

which is as invalid as the former.

On the other hand

 (1 to 3).foreach(print(_))

expands to

 (1 to 3).foreach(x => print(x))

which is perfectly legal.

In short, the _ expands to an explicit lambda parameter, which is then used as argument in the body of the lamba.

serejja
  • 22,901
  • 6
  • 64
  • 72
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235