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 30

Quite the Outspoken Type

Scala's powerful type inference allows you to omit type declarations in many places, leaving the compiler to figure things out. For non-trivial expressions, though, explicitly specifying types is regarded as good practice.

The following example defines two versions of an implicit conversion function from numeric strings to integers: first without, then with, an explicit type declaration. A println statement that relies on the two implicit variants follows. What is the result of executing the following code?

  class QuietType {
    implicit val stringToInt = (_: String).toInt
    println("4" - 2)
  }
  class OutspokenType {
    implicit val stringToInt: String => Int = _.toInt
    println("4" - 2)
  }
    new QuietType()
  new ...

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