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: ...

Get Scala Puzzlers now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.