In the code below, what is the classification (or technical name) of the usage of the underscore character?
scala> def f: Int => Int = _ + 1
f: Int => Int
scala> f(2)
res0: Int = 3
From Functional Programming in Scala
... sometimes called underscore syntax for a function literal, we are not even bothering to name the argument to the function, using _ represent the sole argument. When using this notation, we can only reference the function parameter once in the body of the function (if we mention _ again, it refers to another argument to the function)
In your case, doing:
def f: Int => Int = _ + 1
would be the same thing as this:
def f: Int => Int = x => x + 1
which may seem unnecessary, but becomes pretty handy for passing anonymous functions to higher ordered functions (which are functions that take functions as arguments):
def higherOrder(f: Int => Int) = { /* some implementation */ }
// Using your function you declared already
higherOrder(f)
// Passing an anonymous function
higherOrder((x: Int) => x + 1)
higherOrder((x) => x + 1)
higherOrder(x => x + 1)
// Passing an anonymous function with underscore syntax
higherOrder(_ + 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With