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 9

Init You, Init Me

As your programs get larger, you may end up with modules that have cyclic dependencies. Reliably initializing such modules can be challenging.

What is the result of executing the following code in the REPL?

  object XY {
    object X {
      val value: Int = Y.value + 1
    }
    object Y {
      val value: Int = X.value + 1
    }
  }
    println(if (math.random > 0.5) XY.X.value else XY.Y.value)

Possibilities

  1. Prints:
      1
    
  2. Prints:
      2
    
  3. Prints either:
      1
    

    or:

      2
    
  4. Throws a runtime exception.

Explanation

You may wonder whether the Scala compiler can even handle cyclic definitions of this kind, or whether you will run into an endless loop at runtime.

If you are confident that Scala can indeed handle such definitions without blowing ...

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