1

In Scala 2.9.2

List(List(1,5,4),List(7,9,11)).flatten.map {i => println(i); identity(i) }.find { _ % 2 == 0 }

Prints:

1
5
4
7
9
11
Option[Int] = Some(4)

But

List(List(1,5,4),List(7,9,11)).flatten.map { println("."); identity(_) }.find { _ % 2 == 0 }

Prints

.
Option[Int] = Some(4)

I must admit, I'm slightly suprised by this behavior. Underscore does not seem to be merely a shorthand for the equivalent in-line function, but has other affects on the code. What is going on here?

noahlz
  • 10,202
  • 7
  • 56
  • 75

1 Answers1

7
{ println("."); identity(_) }

is not a function that prints a dot and returns identity. It's a code block that is executed once when the expression is evaluated, prints a single dot, then returns the function identity(_), which in turn is mapped over the flattened list.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • 2
    This explanation is not completely correct. `{ println("."); identity(_) }` contains a function, in fact it is desugared to `{ println("."); x => identity(x) }`. This means the identity function is called for all values of the list. – kiritsuku Nov 21 '13 at 18:08
  • @sschaef I think maybe larsmans said that (the first time :). It is strange that blocks are not mysterious or abstract, but generate many questions and verbiage to answer them. It's not just underscore's fault. – som-snytt Nov 22 '13 at 07:13
  • @som-snytt ok, after reading his sentence again it makes more sense to me. EDIT: he has edited his answer, that is why it makes more sense now to me ;) – kiritsuku Nov 22 '13 at 08:01