Mixing in Traits
Unlike with parents, a class can mix in several traits at once, like a student who joins the choir, chess club, and soccer team. Each trait adds its own abilities.
In this page:
Syntax
class ClassName extends FirstTrait with SecondTrait with ThirdTrait {
// body
}
val obj = new ClassName with ExtraTrait
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Writing
extends Flyable extends Swimmableinstead ofextends Flyable with Swimmable. - Mixing traits that define the same method with different bodies, causing a conflict that requires
override. - Expecting the order of mixed-in traits to be irrelevant, when the order affects which
overrideis called first.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: