← Back to Scala Course | Chapter 8: Inheritance & Traits | Lesson 5 of 7

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:

  1. Mixing in Traits
Syntax
scala
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

markup
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()
}
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
  1. Writing extends Flyable extends Swimmable instead of extends Flyable with Swimmable.
  2. Mixing traits that define the same method with different bodies, causing a conflict that requires override.
  3. Expecting the order of mixed-in traits to be irrelevant, when the order affects which override is called first.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.