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 4

Now You See Me, Now You Don't

Scala supports object-oriented programming concepts, and inheritance is a prominent one. When working with inheritance, it is often useful to override default values set in parent classes and traits. Adding multiple levels of inheritance makes things more interesting, such as in the following program. What does it print?

  trait A {
    val foo: Int
    val bar = 10
    println("In A: foo: " + foo + ", bar: " + bar)
  }
    class B extends A {
    val foo: Int = 25
    println("In B: foo: " + foo + ", bar: " + bar)
  }
    class C extends B {
    override val bar = 99
    println("In C: foo: " + foo + ", bar: " + bar)
  }
    new C()

Possibilities

  1. Prints:
      In A: foo: 0, bar: 0
      In B: foo: 25, bar: 0
      In C: foo: 25, bar: 99
    
  2. Prints: ...

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