TExcelTAD
Home › Scala › Scala Traits

Scala Traits

A trait describes a capability or a role that classes can take on. Like a Java interface, it can declare abstract methods; unlike older interfaces, it can also contain concrete methods and fields. A class extends one class but can mix in many traits.

Defining and implementing a trait

scala · try it yourself
trait Describable:
  def name: String                       // abstract: implementers must define it
  def describe: String = s"This is $name" // concrete: inherited as-is

class Dog(val name: String) extends Describable
class Planet(val name: String, moons: Int) extends Describable:
  override def describe = s"$name, a planet with $moons moons"

@main def run(): Unit =
  val things: List[Describable] = List(Dog("Rex"), Planet("Mars", 2))
  things.foreach(t => println(t.describe))
This is Rex
Mars, a planet with 2 moons

Dog gets describe for free; Planet overrides it.

Mixing in several traits

Use with (or commas in Scala 3) to combine traits. Each trait adds its own behaviour.

scala · try it yourself
trait Swimmer:
  def swim: String = "paddles through water"

trait Flyer:
  def fly: String = "soars through the sky"

trait Walker:
  def walk: String = "waddles along"

class Duck(name: String) extends Swimmer, Flyer, Walker:
  def report: List[String] = List(swim, fly, walk).map(a => s"$name $a")

@main def run(): Unit =
  Duck("Daisy").report.foreach(println)
  val f: Flyer = Duck("Donald")
  println(f.fly)
Daisy paddles through water
Daisy soars through the sky
Daisy waddles along
soars through the sky

Trait parameters

Scala 3 traits can take parameters, just like classes:

scala · try it yourself
trait Greeting(val salutation: String):
  def greet(name: String): String = s"$salutation, $name!"

class EnglishHost extends Greeting("Hello")
class SpanishHost extends Greeting("Hola")

@main def run(): Unit =
  println(EnglishHost().greet("Kim"))
  println(SpanishHost().greet("Kim"))
Hello, Kim!
Hola, Kim!

Stackable modifications

When several traits override the same method and call super, they are applied in linearisation order: the trait mentioned last runs first. This lets you stack small behaviours like decorators.

scala · try it yourself
trait Formatter:
  def format(s: String): String = s

trait Trimmed extends Formatter:
  override def format(s: String): String = super.format(s.trim)

trait Upper extends Formatter:
  override def format(s: String): String = super.format(s.toUpperCase)

trait Exclaimed extends Formatter:
  override def format(s: String): String = super.format(s + "!")

class Shouter extends Formatter, Trimmed, Upper, Exclaimed

@main def run(): Unit =
  println(Shouter().format("   hello there   "))
HELLO THERE   !

Read it right to left: Exclaimed adds ! to the untrimmed text, Upper capitalises, and only then does Trimmed trim — by now the trailing spaces sit before the !, so only the leading spaces are removed. Change the order to Exclaimed, Upper, Trimmed and the result becomes HELLO THERE!.

Traits vs. abstract classes

Trait Abstract class
How many can a class extend? many one
Constructor parameters yes (Scala 3) yes
Concrete methods and fields yes yes
Callable from Java as an interface yes (mostly) as a class
Typical use capabilities, mixins, type hierarchies a base with shared constructor logic

Tip: Prefer traits. Reach for an abstract class mainly when Java code needs to extend your type or when a constructor must do substantial work.

Sealed traits for closed hierarchies

A sealed trait can only be extended in the same file. Pattern matches over it are checked for completeness.

scala · try it yourself
sealed trait Vehicle:
  def wheels: Int

case class Bike(gears: Int) extends Vehicle:
  val wheels = 2
case class Car(seats: Int) extends Vehicle:
  val wheels = 4
case class Truck(axles: Int) extends Vehicle:
  def wheels = axles * 4

def toll(v: Vehicle): Double = v match
  case Bike(_)                  => 0.0
  case Car(seats) if seats > 5  => 4.0
  case Car(_)                   => 3.0
  case Truck(axles)             => 2.5 * axles

@main def run(): Unit =
  val traffic = List(Bike(21), Car(4), Car(7), Truck(3))
  for v <- traffic do println(s"$v: ${v.wheels} wheels, toll ${toll(v)}")
Bike(21): 2 wheels, toll 0.0
Car(4): 4 wheels, toll 3.0
Car(7): 4 wheels, toll 4.0
Truck(3): 12 wheels, toll 7.5

If you delete the Truck case, the compiler warns: match may not be exhaustive. It would fail on pattern case: Truck(_).

Test yourself

How many traits can a Scala class mix in?

  1. Only one
  2. At most two
  3. As many as needed
  4. None, only abstract classes

Can a trait contain concrete (implemented) methods?

  1. No, only abstract ones
  2. Yes
  3. Only private ones
  4. Only in Scala 2

What does sealed add to a trait?

  1. It cannot have methods
  2. All subtypes must be defined in the same file, enabling exhaustiveness checks
  3. It becomes a singleton
  4. It cannot be extended at all