Mixing in Traits
In this page:
Mixing in Traits
Unlike classes, a Scala class can mix in multiple traits at once using extends Trait1 with Trait2 with Trait3, combining behavior from several independent sources. This is Scala's safe alternative to multiple inheritance, resolved through a well-defined linearization order rather than ambiguous conflicts. Order matters when traits override the same method -- the rightmost trait's version generally takes precedence in the chain.
Note: Use with to mix in additional traits beyond the first, like class C extends TraitA with TraitB with TraitC.
Example: Mixing in Traits
trait Flyable {
def fly(): Unit = println("Flying")
}
trait Swimmable {
def swim(): Unit = println("Swimming")
}
class Duck extends Flyable with Swimmable
object Main extends App {
val duck = new Duck()
duck.fly()
duck.swim()
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: