2

I've been trying my best to understand the underscore syntax and I've found various threads involving this but I'm still unclear on one use:

I see this in Odersky's book (pg 150 and 151 in Version 3)

someNumbers.foreach(println _)

Apparently this replaces an entire parameter list? I don't see how this is different from a normal placeholder. It goes on to say that this is not a placeholder for a single parameter... it is a placeholder for an entire list. This is unclear to me. How is this different from a placeholder?

Is this the same concept:

def add(x: Int, y: Int) = x + y
val addFunction = add _
// Does this just copy the parameter list?
addFunction(1,2)
Jwan622
  • 11,015
  • 21
  • 88
  • 181

1 Answers1

3

In add _ or println _ the underscore is not a placeholder. You can see it if you replace add _ with add(_) in your second example. In this case, the code will not compile. If it was a placeholder, you could switch the syntaxes.

It is called eta-expansion and is used to convert a method into a function. In Scala thoses two notions are a little bit different :

  • A function can be defined with the syntax: val fn: A => B = (a: A) => ...
  • A method is defined with the syntax: def fn(a: A): B = ...

Generally, the two syntaxes can be used indifferently. But sometimes it is required to explicitly transform a method into a function with this syntax.

You can find more informations here : What is the eta expansion in Scala?

Eaque
  • 1,348
  • 1
  • 9
  • 7