Traits in Scala

Ruining (Ray) Li
1 min readMay 4, 2021

Traits in Scala are like Java interfaces with concrete methods.

Traits can also declare fields and maintain state.

A class can mix in multiple traits.

Usage 1: Widen thin interfaces to rich ones

This is achievable because traits allow concrete methods.

E.g., Ordered trait

Define a single compare method; the Ordered trait then defines <. >, ≤, ≥ for you in terms of this compare method.

Usage 2: Define stackable modifications

The following is not acceptable for normal classes — because super has no concrete implementation!

abstract class IntQueue {
def get(): Int
def put(x: Int): Unit
}
// A concrete class BasicIntQueue
class BasicIntQueue extends IntQueue {
// Implementation of get() and put(x: Int)
}
trait Doubling extends IntQueue {
abstract override def put(x: Int) = { super.put(2*x) }
}
trait Incrementing extends IntQueue {
abstract override def put(x: Int) = { super.put(x+1) }
}
trait Filtering extends IntQueue {
abstract override def put(x: Int) = { if(x >= 0) super.put(x) }
}

Examples:

val queue = new BasicIntQueue with Incrementing with Filtering
queue.put(-1); queue.put(0); queue.put(1)
queue.get() // 1
queue.get() // 2
val queue. = new BasicIntQueue with Filtering with Incrementing
queue.put(-1); queue.put(0); queue.put(1)
queue.get() // 0
queue.get() // 1
queue.get() // 2

⬆️: The order of mixins is significant!

General rule: traits further to the right take effect first.

--

--

Ruining (Ray) Li

From Oxford. Studying Computer Science and on my way to a badass geek.