Traits and linearization

A trait is a type that a class can mix in. It may declare members without a body, provide members with one, and hold state; a class that extends it gets all of them and may override what it needs. A class extends one class and any number of traits, and the order of the traits decides which super call runs first.

A trait with a member

Greeter declares an abstract name and a concrete greet built from it. Counted adds a field and a method. Person mixes both in and provides the two abstract members as constructor parameters:

traits.scala

trait Greeter: def name: String def greet: String = s"Hello, $name" trait Counted: val id: Int def label: String = s"#$id" class Person(val name: String, val id: Int) extends Greeter, Counted @main def traits(): Unit = val person = new Person("Ada", 7) println(person.greet) println(person.label)

scala-cli run --server=false traits.scala

Hello, Ada
#7

A trait is not an interface with default methods only: Counted declares an abstract val, and its concrete label reads the value the class supplies. That is why a trait can be the whole of a small abstraction and need no class of its own.

The order of super calls

Two traits may override the same method and call super. Which one runs first is decided by the linearization: the class itself, then the traits from right to left, then the base. Both declares Base, Loud, Excited, so Excited is the outermost:

linearization.scala

trait Base: def describe: String = "base" trait Loud extends Base: override def describe: String = super.describe.toUpperCase trait Excited extends Base: override def describe: String = super.describe + "!" class Both extends Base, Loud, Excited @main def linearization(): Unit = println((new Both).describe)

scala-cli run --server=false linearization.scala

BASE!

Excited calls super.describe, which is Loud, which calls super.describe, which is Base: the string is built inside out, so the upper case happens before the exclamation mark. Reversing the two traits in the extends clause reverses the result, which is the whole reason the order is written down.

Related

Автор статьи: Arthur Isaev