user1730177
user1730177

Reputation: 91

What is the meaning or use of { _ => } and _ = somefunctionname() in scala

As in the question, why do people write code in the most confusing manner in scala as in

    _ = function1(arg1, arg2)

and

    anObject.method(arg1, arg2) { _ => } 

which I fail to understand what it does.

Upvotes: 2

Views: 199

Answers (1)

Oleg Pyzhcov
Oleg Pyzhcov

Reputation: 7353

The first question has to do with monadic style. Inside for-comprehensions, it is not possible to simply call a function.

for {
    x <- getList // <- I don't need this x!
    y = func(42)
    println(y) // <- I cannot do this!
} yield y

Sometimes, however, you are not interested in results and therefore don't want to give it a name.

At least Scala allows you to discard these results using an underscore:

for {
    _ <- getList // <- somewhat better
    y = func(42)
    _ = println(y) // <- somewhat dumb, but better than not being able to
} yield y

Scala also allows you to use underscore when you are not interested in an argument of a function, e.g.:

List.tabulate(3, 3)((x, _) => x) // we omitted second argument

produces 3x3 list with all rows having the same number

List(
  List(0, 0, 0),
  List(1, 1, 1),
  List(2, 2, 2)
)

Finally, a block with no statements is considered a block returning Unit (which is like void in java)

As a less abstract example, you can consider an iterator that does something when evaluated:

val it = Iterator.from(1).map(x => { println(s"x is $x"); x }).take(3)

Iterators are lazy, so nothing would happen until we convert it into a collection or call foreach. If we only care about side-effects, it's possible to write:

it.foreach { _ => }

Only after this output will be seen:

x is 1
x is 2
x is 3

Upvotes: 15

Related Questions