Mixins are traits that are used to compose classes in Scala.
Let’s suppose we want to represent a simple entity, such as a computer. To present this entity, we can use a trait:
trait Computer {
def model: String
def storage: Int
def ram: Int
}
We can use the Computer
trait
to construct more specific entities, as shown here:
class Laptop(val model: String,
val storage: Int,
val ram: Int ) extends Computer
As the Laptop
class extends Computer
, it implements the fields of the Computer
trait
. Let’s see this in code:
trait Computer {def model: Stringdef storage: Intdef ram: Int}class Laptop(val model: String,val storage: Int,val ram: Int ) extends Computerval laptop = new Laptop("Lenovo T430", 240,4 )println(laptop.model)println(laptop.storage)println(laptop.ram)
Now, let’s imagine we want to calculate a performance index of the Computer
instances. Scala provides us the functionality to enrich our class via the traits mixin. This neat approach doesn’t require us to rewrite the code of our class.
Once we’ve extended a class from another class, we can further mix it with another one. In our case, using an Index
trait would suffice. This new trait
extends the Computer
trait
and has access to its fields model
, storage
, and ram
.
trait Index extends Computer {
def calculateIndex: Int =
(ram*4) + (storage/3)
}
Now, if we want the Laptop
class to calculate the performance index of its instances, we can use the with keyword to mix in the Index
trait
, as we can see here:
trait Computer {def model: Stringdef storage: Intdef ram: Int}class Laptop(val model: String,val storage: Int,val ram: Int ) extends Computertrait Index extends Computer {def calculateIndex: Int =(ram*4) + (storage/3)}val laptopWithIndex = new Laptop("Lenovo T430", 240,4) with Indexprintln("Performance index: " + laptopWithIndex.calculateIndex)
In the code above, we create an instance of the Laptop
class named laptopWithIndex
and mix it with the Index
trait. Then we call the calculateIndex
method on the new instance.
Free Resources