By user1730177


2018-02-13 13:01:35 8 Comments

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.

1 comments

@Oleg Pyzhcov 2018-02-13 13:18:46

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

Related Questions

Sponsored Content

23 Answered Questions

[SOLVED] What is tail recursion?

24 Answered Questions

44 Answered Questions

[SOLVED] What is a monad?

8 Answered Questions

[SOLVED] What are all the uses of an underscore in Scala?

  • 2011-11-03 19:43:45
  • Ivan
  • 113925 View
  • 448 Score
  • 8 Answer
  • Tags:   scala

18 Answered Questions

4 Answered Questions

[SOLVED] What does the `#` operator mean in Scala?

  • 2012-02-25 09:57:16
  • Freewind
  • 11199 View
  • 107 Score
  • 4 Answer
  • Tags:   scala type-systems

2 Answered Questions

[SOLVED] Where does Scala look for implicits?

4 Answered Questions

[SOLVED] What is "lifting" in Scala?

11 Answered Questions

[SOLVED] How to use java.String.format in Scala?

18 Answered Questions

Sponsored Content