Scala Traits
Declaring and Mixing In Traits
A trait may declare abstract members, which mixing classes must implement, and concrete members, which they inherit. A class extends at most one class but may mix in many traits: the first parent follows extends and the rest follow with (Scala 3 also accepts commas).
Abstract and Concrete Members
trait Named {
def name: String // abstract: no body
def greet(): String = s"Hello, $name" // concrete: uses the abstract member
}
trait Logged {
def log(message: String): Unit = println(s"[log] $message")
}
class Customer(val name: String) extends Named with Logged // val name implements def name
@main def traitsBasics(): Unit = {
val c = Customer("Ana")
c.log(c.greet()) // [log] Hello, Ana
}
A val parameter can implement an abstract def without parameters, as name does here. The reverse is not allowed: a def cannot implement an abstract val, because a val promises the same value on every access.
Trait Parameters
Since Scala 3, traits can take parameters, like classes. Only the class that directly extends the trait passes the arguments; this removes the old workarounds with abstract fields that had to be initialized in a particular order.
trait Greeting(val salutation: String) {
def greet(who: String): String = s"$salutation, $who!"
}
class EnglishGreeter extends Greeting("Hello")
class FrenchGreeter extends Greeting("Bonjour")
@main def greetings(): Unit = {
println(EnglishGreeter().greet("Ana")) // Hello, Ana!
println(FrenchGreeter().greet("Ana")) // Bonjour, Ana!
}
Linearization and Stackable Traits
When several traits define the same method, Scala does not report an ambiguity. It orders the class and all its traits into a single line, the linearization, and searches it from right to left: the trait mixed in last comes first. Inside a trait, super refers to the next element in that line, not to a fixed parent. This makes traits stackable.
Stackable Modifications
A trait that extends a class and marks its method abstract override can modify the behavior of whatever implementation comes after it in the line. The order of mixing then decides the order of the modifications:
abstract class Formatter {
def format(s: String): String
}
class Plain extends Formatter {
def format(s: String): String = s
}
trait Trimmed extends Formatter {
abstract override def format(s: String): String = super.format(s.trim)
}
trait Bracketed extends Formatter {
abstract override def format(s: String): String = super.format(s"<$s>")
}
@main def stacking(): Unit = {
val x = new Plain with Trimmed with Bracketed // Bracketed runs first, then Trimmed
val y = new Plain with Bracketed with Trimmed // Trimmed runs first, then Bracketed
println(x.format(" hi ")) // < hi >
println(y.format(" hi ")) // <hi>
}
In x, Bracketed wraps the raw text first, so the spaces are inside the brackets and trimming finds nothing to remove. In y, the text is trimmed before it is wrapped. Stackable traits suit cross-cutting behavior such as logging, validation, caching or retries, added piece by piece around a core implementation.
Resolving Conflicts Explicitly
If a class mixes in two traits with the same concrete method and they do not extend a common base with abstract override, the class must override the method itself. It can call a specific parent with a qualified super, for example super[Logged].log(message).
Self Types
A self type states that a trait can only be mixed into something that is also of another type, without extending that type. It expresses a requirement rather than an is-a relationship, and is a lightweight way to declare dependencies between components.
Declaring a Requirement
trait Database {
def query(sql: String): List[String]
}
trait Reports { self: Database => // whoever mixes in Reports must also be a Database
def userReport(): String = query("select name from users").mkString(", ")
}
class App extends Reports with Database { // compiles only because Database is mixed in
def query(sql: String): List[String] = List("ana", "bo")
}
@main def selfTypes(): Unit = println(App().userReport()) // ana, bo
Inside Reports, the members of Database are available as if inherited, yet Reports itself is not a Database and a user of Reports does not see query through it.
Sealed Traits and Data Modeling
Marking a trait sealed means all its direct subtypes must be defined in the same file. The compiler then knows every case, and warns when a match forgets one — ideal for data with a fixed set of variants.
Exhaustive Matching
sealed trait Shape
case class Circle(radius: Double) extends Shape
case class Square(side: Double) extends Shape
def area(shape: Shape): Double = shape match {
case Circle(r) => math.Pi * r * r
case Square(a) => a * a
} // removing a case produces a "match may not be exhaustive" warning
In Scala 3 the same model can be written more briefly as an enum with parameterized cases, enum Shape { case Circle(radius: Double); case Square(side: Double) }. Pattern matching itself is covered in Control Flow.
Traits or Abstract Classes?
Choosing Between Them
| Aspect | Trait | Abstract class |
|---|---|---|
| How many can a class have | any number | one |
| Constructor parameters | yes, since Scala 3 | yes |
Stackable with abstract override | yes | no |
| Called from Java code | as an interface; concrete members need care | as an ordinary abstract class |
Default to traits: they compose freely. Prefer an abstract class when Java code must extend the type, or when the type is a true base of a hierarchy that should not be combined with others. Classes themselves are covered in Classes.
Practice
Exercises
- Add a
Censoredtrait to the formatter example that replaces a forbidden word, and find a mixing order where censoring happens before trimming. - Write a trait
Cachedwith anabstract overrideofquerythat remembers results in aMap, and stack it onto theAppfrom the self-type example. - Model a traffic light as a sealed trait with three case objects and write a function that returns the next light; then delete one case from the match and read the warning.