Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the usage of _ in Int => Int = _ + 1 [duplicate]

Tags:

scala

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
like image 455
Polymerase Avatar asked Jan 05 '17 14:01

Polymerase


1 Answers

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)
like image 155
Tyler Avatar answered Oct 11 '22 07:10

Tyler