Using modules

We already established that modules and objects are also unified in Scala. This means that we can pass an entire module around our application. It would be useful, however, to show what a module actually looks like. Here is an example:

trait Tick {  trait Ticker {    def count(): Int    def tick(): Unit  }  def ticker: Ticker}

Here, Tick is just an interface to one of our modules. The following is its implementation:

trait TickUser extends Tick {  class TickUserImpl extends Ticker {    var curr = 0        override def count(): Int = curr        override def tick(): Unit = {      curr = curr + 1    }  }  object ticker extends TickUserImpl}

The TickUser trait is an actual module. It implements Tick and contains the code hidden inside it. We create a singleton object ...

Get Scala Design Patterns - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.