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 28

Pick a Value, AnyValue!

Scala's abstract type members allow you to define base classes without immediately committing to specific implementation types. You could, for instance, define a Recipe without having to decide up front how precise you need the amounts to be, i.e., which numeric type to use for quantities:

  trait Recipe {
    type T <: AnyVal
    def sugarAmount: T
    def howMuchSugar() {
      println(s"Add ${sugarAmount} tablespoons of sugar")
    }
  }
    val approximateCake = new Recipe {
    type T = Int
    val sugarAmount = 5
  }
    scala> approximateCake.howMuchSugar()
  Add 5 tablespoons of sugar
    val gourmetCake = new Recipe {
    type T = Double
    val sugarAmount = 5.13124
  }
    scala> gourmetCake.howMuchSugar()
  Add 5.13124 tablespoons of sugar ...

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