Question: What is the usage of _ in Int => Int = _ + 1

Question

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

Answers 2
Added at 2017-01-05 15:01
Tags
Question

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
Answers to

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

nr: #1 dodano: 2017-01-05 15:01

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)
nr: #2 dodano: 2017-01-06 04:01

Think of it as an input which will be supplied by caller

scala> def incrementByOne: Int => Int = _ + 1
incrementByOne: Int => Int

What yo get back is a function that takes Int and returns an Int.

X => Y

In return type means a function that take type X as input and return type Y as output. now X and Y could be any types.

To complete the example, you would call it as

scala> incrementByOne(10)
res0: Int = 11

scala> incrementByOne(99)
res1: Int = 100

scala> 

which took Int as input (10 and 99) and returned Int as output (11 and 100)

Source Show
◀ Wstecz