5

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
Polymerase
  • 6,311
  • 11
  • 47
  • 65

2 Answers2

10

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)
Tyler
  • 17,669
  • 10
  • 51
  • 89
0

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)

daydreamer
  • 87,243
  • 191
  • 450
  • 722
  • thanks for the clarification. I was looking for a syntactic "name" when the underscore is used in such a way in an anonymous function. From the link given in the 1st post. [What are all the uses of an underscore in Scala?](http://stackoverflow.com/questions/8000903/what-are-all-the-uses-of-an-underscore-in-scala). It is called "Placeholder Syntax". Not really intuitive but it's Ok as long as there is a name. – Polymerase Jan 06 '17 at 23:01