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 14

Return to Me!

Unlike Java, Scala does not require methods returning a value to contain an explicit return statement. If omitted, the method will inherently return the result of the last expression.

Occasionally, though, explicit return statements do show up in Scala code. In fact, a single method can contain multiple return expressions, as in the following program. What does it do?

  def sumItUp: Int = {
    def one(x: Int): Int = { return x; 1 }
    val two = (x: Int) => { return x; 2 }
    1 + one(2) + two(3)
  }
    println(sumItUp)

Possibilities

  1. Prints:
      3
    
  2. Prints:
      4
    
  3. Prints:
      6
    
  4. Fails to compile with an error: unreachable code.

Explanation

Something that immediately stands out in this code are the number literals, 1 and 2, which appear ...

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