Skip to main content

Traits

A trait is a contract: the bindings a type promises to provide. It says what, and leaves how to the type:

trait Faculty {
let firstName : string
let lastName : string

let sayHello()
}

A class implements a trait with : TraitName, and marks each member it provides with override. override is required, so a typo can't quietly make a new member instead:

trait Faculty {
let firstName : string

let sayHello()
}

class Teacher : Faculty {
override let firstName : string

new(name: string) {
firstName = name
}

override let sayHello() {
println("Hello ${firstName}. I am a teacher.")
}
}

Default members​

A trait can give a member a body. A type that implements the trait gets it as it is, or replaces it with override:

trait Greeter {
let name() : string

let greet() = "Hello, ${name()}"
}

class English : Greeter {
override let name() = "world"
}

A trait that extends a trait​

A trait can build on another. A type that implements it promises both:

trait Named {
let name() : string
}

trait Labelled : Named {
let label() : string
}

A variable whose type is a trait holds any type that implements it, so code written against Faculty works for every kind of faculty.