At first I had believed that using underscores to make closures (e.g. println _
) were just shorthand for using an arrow (e.g. x => println x
), but I just recently learned that you can also do the following:
def f(a: Int, b: Int) = a + 2 * b
List(1, 2, 3).reduce(f _)
Given my past assumptions, f _
looks like a closure that accepts exactly one argument and passes exactly one argument to f
. I assumed it would tell me it couldn't compile because f
expects two arguments, and reduce
should expect a function with two arguments. But it works as if I had written:
def f(a: Int, b: Int) = a + 2 * b
List(1, 2, 3).reduce((x, y) => f(x, y))
What is going on here? What are the rules for creating closures with underscores?