Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 37 ยท Classes, Traits and Objects

Traits and Mixins

Learn Scala traits: abstract and concrete members, mixing in several traits, stackable behaviour, linearization order, trait parameters, and when to use a trait or abstract class.

A trait is a reusable bundle of members that a class can mix in. It is like a Java interface that may also carry method bodies and fields. Because a class can extend many traits, traits are how Scala shares behaviour without multiple class inheritance. They are everywhere: Ordered, Iterable, Product, and most of the collection types are traits. In this lesson you will define traits, mix them into classes and objects, stack them, and understand the order Scala uses to resolve conflicts. The Scala code is read-only; runnable Java and Kotlin interfaces show the equivalent ideas.

A basic trait

SCALA
trait Greeter:
  def name: String                       // abstract
  def greet: String = s"Hello, $name!"   // concrete

class Person(val name: String) extends Greeter

Person("Ada").greet      // Hello, Ada!

A trait uses extends for the first parent and with for more (in Scala 3 you can also separate them with commas):

SCALA
trait Walker:
  def walk: String = "walking"
trait Swimmer:
  def swim: String = "swimming"

class Duck extends Walker, Swimmer       // Scala 3 comma style
class Duck2 extends Walker with Swimmer  // classic style

val d = Duck()
d.walk     // walking
d.swim     // swimming

A trait cannot be instantiated alone (Greeter() fails) unless it is anonymous:

SCALA
val g = new Greeter:
  def name = "anon"
g.greet    // Hello, anon!

Java's default methods on interfaces and Kotlin interfaces with bodies play the same role. Run the Kotlin version:

Kotlin Interfaces with default bodies (Kotlin comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Traits with state

Unlike a Java interface, a trait may hold fields:

SCALA
trait Counter:
  private var count = 0
  def increment(): Int =
    count += 1
    count

class Clicks extends Counter

val c = Clicks()
c.increment()    // 1
c.increment()    // 2

Each instance that mixes in the trait gets its own count. Use this carefully: shared mutable state in traits makes classes harder to reason about.

Mixing in at creation

You can add a trait to a single instance when you create it:

SCALA
class Account(var balance: Double)

trait Audited:
  def audit(msg: String): Unit = println(s"[audit] $msg")

val acc = new Account(10) with Audited
acc.audit("created")     // [audit] created

Stackable modifications

Traits can modify the behaviour of what they are mixed with by overriding a method and calling super. That makes it possible to stack small features:

SCALA
abstract class Text:
  def render: String

class Plain(s: String) extends Text:
  def render: String = s

trait Exclaim extends Text:
  abstract override def render: String = super.render + "!"

trait Brackets extends Text:
  abstract override def render: String = "[" + super.render + "]"

val t1 = new Plain("hi") with Exclaim with Brackets
val t2 = new Plain("hi") with Brackets with Exclaim

t1.render   // "[hi!]"
t2.render   // "[hi]!"

The only difference between t1 and t2 is the order of the traits, and the results differ. abstract override tells the compiler that super.render will be provided by whatever the trait is mixed into.

Linearization: which super is called?

For a class with several traits, Scala builds a single line of ancestors. A super call goes to the next type in that line, reading from right to left in the extends clause. For t1 (Plain with Exclaim with Brackets) the calls go:

  1. Brackets.render (rightmost, called first) calls super.render
  2. which is Exclaim.render, which calls super.render
  3. which is Plain.render, returning "hi"
  4. Exclaim makes it "hi!", then Brackets wraps it as "[hi!]"

So the rightmost trait wraps everything to its left. The same idea in Java using function composition, runnable:

Java Order of decoration (Java comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Traits vs abstract classes

Trait Abstract class
How many can a class extend? many one
Constructor parameters allowed in Scala 3 allowed
Java interop default methods in interface (Scala 2.12+) normal abstract class
Best for capabilities, mixins ("can do X") a base with shared state and identity ("is a X")

A common rule: start with a trait; use an abstract class when you need constructor arguments that Java code will call, or you want to prevent mixing into unrelated classes.

Trait parameters (Scala 3)

Scala 3 lets traits take parameters, like classes:

SCALA
trait Named(val name: String):
  def hello = s"I am $name"

class Cat extends Named("Tom")

Cat().hello     // I am Tom

A trait with parameters must be given its arguments the first time it appears in the inheritance chain.

Self types

A trait can state that it needs to be mixed into something that provides other members, using a self type:

SCALA
trait Logging:
  def log(msg: String): Unit = println(s"LOG: $msg")

trait UserService:
  self: Logging =>
  def create(name: String): Unit =
    log(s"creating $name")

class App extends UserService, Logging

App().create("ada")     // LOG: creating ada

UserService does not extend Logging, but it requires that the final class does. This is the "cake pattern" building block. Today most Scala code prefers constructor injection with plain parameters or using clauses; you will see self types mostly in older frameworks.

Universal traits and sealed traits

  • sealed trait limits implementers to the same file and enables exhaustive match checking.
  • Marker traits (no members) tag types, such as Serializable.
  • Traits can extend classes: trait Foo extends Bar means only subclasses of Bar can mix it in.

Common mistakes

  • Expecting trait order to be irrelevant. Linearization makes it matter.
  • Putting mutable state in traits that many classes mix in.
  • Forgetting abstract override on stackable traits that call super on an abstract method.
  • Defining a deep web of traits where simple functions would do.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How can a class use several traits?

    A class extends one parent and may mix in many traits with with or commas in Scala 3.
  2. 2. What is a major difference between a trait and a Java 7 interface?

    Traits can contain method bodies and state, unlike a Java 7 interface.
  3. 3. In new Plain("hi") with Exclaim with Brackets, which trait's render is called first?

    Linearization puts the rightmost trait first (here Brackets), and its super call walks left.
  4. 4. What does self: Logging => inside a trait mean?

    A self type declares a requirement on the final class without making the trait a subtype of Logging.

Summary

  • A trait bundles abstract and concrete members and can be mixed into many classes with extends and with/commas.
  • Traits may hold state and, in Scala 3, take parameters.
  • Mixing in at creation (new C with T) adds behaviour to a single instance.
  • Linearization decides super calls: the rightmost trait wraps those to its left.
  • Use a trait for capabilities and an abstract class for a base with identity; self types express required collaborators.

Next: Packages, Imports and Access Control