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

Mixing in Traits

In this page:

  1. Mixing in Traits

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()
}
🔒

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.