Skip to content
Scala

Traits and Mixins

Compose behaviors using traits with default implementations.

By EZ4Code Team
traitmixincomposition

Code

trait Logger {
  def log(msg: String): Unit = println(s"[LOG] $msg")
}

trait TimestampedLogger extends Logger {
  override def log(msg: String): Unit =
    super.log(s"${System.currentTimeMillis()} - $msg")
}

class Service extends TimestampedLogger {
  def run(): Unit = log("Service started")
}

// Linearization: Service -> TimestampedLogger -> Logger
new Service().run()
// [LOG] 1700000000000 - Service started

Explanation

Traits are Scala's interface with optional implementations. Multiple traits can be mixed in (stackable modification), and the linearization order determines how super calls resolve. This enables flexible composition without deep inheritance hierarchies.

More Scala Snippets