This is an excerpt from the Scala Cookbook. This is Recipe 8.4, “How to use Scala traits as simple mixins (or, How to mix in Scala traits).”
Problem
You want to design a solution where multiple Scala traits can be mixed into a class to provide a robust design.
Solution
To implement a simple mixin in Scala, define the methods you want in your trait, then add the trait to your class using extends
or with
. For instance, the following code defines a Tail
trait:
trait Tail { def wagTail = println("tail is wagging") def stopTail = println("tail is stopped") }
You can use this trait with an abstract Pet
class to create a Dog
:
abstract class Pet (var name: String) { def speak // abstract def ownerIsHome = println("excited") def jumpForJoy = println("jumping for joy") } class Dog (name: String) extends Pet (name) with Tail { def speak = println("woof") override def ownerIsHome { wagTail speak } }
The Dog
class extends the abstract class Pet
and mixes in the Tail
trait, and can use the methods defined by both Pet
and Tail
:
object Test extends App { val zeus = new Dog("Zeus") zeus.ownerIsHome zeus.jumpForJoy }
In summary, the Dog
class gets behavior from both the abstract Pet
class and the Tail
trait; this is something you can’t do in Java.
To see a great demonstration of the power of mixins, read Artima’s short “Stackable Trait Pattern” article. By defining traits and classes as base, core, and stackable components, they demonstrate how sixteen different classes can be derived from three traits by “stacking” the traits together.
this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |
See Also
When you develop traits, you may want to limit the classes they can be mixed into. The classes a trait can be mixed into can be limited using the following techniques:
- Recipe 8.5 shows how to limit Scala which classes can use a trait by declaring inheritance
- Recipe 8.6 shows how to mark Scala traits so they can only be used by subclasses of a certain type
- Recipe 8.7 demonstrates the technique to use to make sure a Scala trait can only be mixed into classes that have a specific method
- Also, see Artima’s “Stackable Trait Pattern”