O'Reilly logo

Scala Puzzlers by Nermin Šerifovic, Andrew Phillips

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Puzzler 15

Count Me Now, Count Me Later

Scala uses the underscore character (_) as a wildcard symbol quite extensively. The following program focuses on two uses of this symbol. What does it print?

  var x = 0
  def counter() = { x += 1; x }
  def add(a: Int)(b: Int) = a + b
  val adder1 = add(counter)(_)
  val adder2 = add(counter) _
    println("x = " + x)
  println(adder1(10))
  println("x = " + x)
  println(adder2(10))
  println("x = " + x)

Possibilities

  1. Prints:
      x = 1
      12
      x = 2
      11
      x = 2
    
  2. Prints:
      x = 1
      11
      x = 1
      12
      x = 2
    
  3. Prints:
      x = 0
      11
      x = 1
      12
      x = 2
    
  4. Prints:
      x = 2
      11
      x = 2
      12
      x = 2
    

Explanation

The lines that define counter, adder1, and adder2 seem to be crucial in the code snippet, so let's focus on fully understanding them. The counter method definition ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required