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 startedExplanation
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
Pattern Matching
Destructure values and match cases in Scala.
Case Classes
Immutable data classes with auto-generated equals/hashCode/toString.
Collections Operations
Functional collection operations: map, filter, fold, groupBy.
Futures and Async
Asynchronous computation with Future and ExecutionContext.
Implicits (Given/Using in Scala 3)
Type-class derivation and context passing via implicits.
Akka Actors (Pekko)
Message-passing concurrency with the actor model.