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 3

Location, Location, Location

In many object-oriented languages, it is common to accept parameters in a class constructor for the purpose of assigning them to class members:

  class MyClass(param1, param2, ...) {
    val member1 = param1
    val member2 = param2
    ...
  }

Scala, which favors concise code, lets you avoid this redundancy by declaring members and constructor parameters in one go:

  class MyClass(val member1, val member2, ...) {
    ...
  }

What is the result of executing the following code?

  trait A {
    val audience: String
    println("Hello " + audience)
  }
    class BMember(a: String = "World"extends A {
    val audience = a
    println("I repeat: Hello " + audience)
  }
    class BConstructor(val audience: String = "World"extends A {   println( ...

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