Traits

A trait names methods that several obj types have. Code written for the trait works with any of them: a list can hold circles and rectangles together, and a function can take any shape.

trait Shape {
    fn area(): float
    fn name(): str
}

obj Circle: Shape {
    r: float

    fn area(): float {
        return 3.14 * self.r * self.r
    }
    fn name(): str {
        return "circle"
    }
}

obj Rect: Shape {
    w: float
    h: float

    fn area(): float {
        return self.w * self.h
    }
    fn name(): str {
        return "rectangle"
    }
}

fn report(s: Shape) {
    print("${s.name()}: ${s.area()}")
}

shapes: [Shape] = [Circle { r: 1.0 }, Rect { w: 2.0, h: 3.0 }]
shapes.walk(s) {
    report(s)
}

Output:

circle: 3.14
rectangle: 6.0
  • trait Shape { ... } lists methods, as in an obj, but without their code: just fn name(parameters): result. (It can also give code for some.)
  • obj Circle: Shape { ... } says that a Circle is a Shape. The obj must then have each of the trait’s methods, with the same parameter and result types.
  • Shape is a type: for variables, parameters, results, list and map elements, and fields.
  • s.area() runs the method of the object’s own type: Circle’s area for a circle, Rect’s for a rectangle.

An obj that is a trait

After the obj’s name and a colon come the traits it is, separated by commas, like the type after a variable’s name:

trait Named {
    fn name(): str
}
trait Priced {
    fn price(): int
}

obj Book: Named, Priced {
    title: str
    cents: int

    fn name(): str {
        return self.title
    }
    fn price(): int {
        return self.cents
    }
    fn pages(): int {
        return 300
    }
}

b: Book = Book { title: "Luma", cents: 1500 }
n: Named = b
p: Priced = b
print("${n.name()} costs ${p.price()}")

Output:

Luma costs 1500

The obj can have more fields and methods than its traits ask for (pages here); through the trait, only the trait’s methods are visible.

The compiler checks the obj against its traits, and says what is missing at the obj:

obj Book: Named, Priced {      // error: Book is a Priced, so it needs the method fn price(): int

Trait values

An object goes into a trait variable as it is: it is shared, not copied, like every object. A change through one name is seen through the other:

trait Counter {
    fn add()
    fn total(): int
}

obj Clicks: Counter {
    n: int = 0

    fn add() {
        self.n = self.n + 1
    }
    fn total(): int {
        return self.n
    }
}

c: Clicks = Clicks {}
counter: Counter = c
counter.add()
counter.add()
print(c.n)
print(counter)

Output:

2
Clicks {n: 2}
  • Only the trait’s methods can be used through a trait value: counter.n is an error (counter is a Counter, a trait: only its methods can be used, not fields).
  • print and ${...} show the object itself, with its own type: Clicks {n: 2}.
  • A trait value always holds an object; there is no empty one.
  • Trait values can’t be compared with ==, like objects.

Traits as fields

A field can have a trait type, for a part that can be swapped: a logger that writes to a file or keeps the lines, a storage that is a database or a map in tests.

trait Logger {
    fn log(line: str)
}

obj Screen: Logger {
    fn log(line: str) {
        print("[log] ${line}")
    }
}

obj Shop {
    logger: Logger = Screen {}
    sold: int = 0

    fn sell(item: str) {
        self.sold = self.sold + 1
        self.logger.log("sold ${item}")
    }
}

shop: Shop = Shop {}
shop.sell("tea")

Output:

[log] sold tea

The default of a trait field is an object of an obj type that is the trait, as here, or the field is given when the object is made: Shop { logger: Screen {} }.

In an obj with init, a trait field can go without a default: init sets it. It must do so first, before anything else uses self, so that the field is never without a value:

trait Store {
    fn get(key: str): str
}

obj Memory: Store {
    data: {str: str} = {}

    fn get(key: str): str {
        return self.data[key]
    }
}

obj App {
    store: Store
    calls: int = 0

    fn init(s: Store) {
        self.store = s
        self.calls = 0
    }

    fn lookup(key: str): str {
        self.calls = self.calls + 1
        return self.store.get(key)
    }
}

m: Memory = Memory { data: {"lang": "Luma"} }
app: App = App(m)
print(app.lookup("lang"))

Output:

Luma
fn init(s: Store) {
    self.log("start")       // error: store has no default, so init must set it first: self.store = ... at the start of init, before anything else uses self
    self.store = s
}

Traits from other files

A trait is shared with other files with pub trait, like pub obj. Other files write it with the file’s name: geo.Shape, both to use it as a type and to make their own objs one:

File geo.luma:

pub trait Shape {
    fn area(): float
}
import "geo"

obj Square: geo.Shape {
    side: float

    fn area(): float {
        return self.side * self.side
    }
}

s: geo.Shape = Square { side: 3.0 }
print(s.area())

Output:

9.0

Code in a trait

A trait’s method can have code of its own. Each obj that is the trait then has that method without writing it, and an obj can still write its own instead:

trait Named {
    fn name(): str
    fn greet(): str => "Hello, ${self.name()}!"
    fn shout(): str {
        return self.greet().upper()
    }
}

obj Dog: Named {
    nick: str
    fn name(): str => self.nick
}
obj Robot: Named {
    fn name(): str => "R2"
    fn greet(): str => "BEEP ${self.name()}"
}

d: Dog = Dog{nick: "Rex"}
print(d.greet())
print(d.shout())
r: Named = Robot{}
print(r.shout())

Output:

Hello, Rex!
HELLO, REX!
BEEP R2
  • In the trait’s code, self is the trait: it can use the trait’s methods, not fields (a trait has none). A call like self.greet() reaches the object’s own method, so Robot’s shout uses Robot’s greet.
  • An obj’s own has the same header as the trait’s; it replaces the trait’s code for that obj.
  • Like any method: d.greet(), through the trait, and as a value: Dog.greet is a fn(Dog): str, and Named.shout a fn(Named): str.
  • Two traits with code for the same method: an obj that is both writes its own (the compiler asks for it), so it’s clear which one it has.
  • An obj’s own method can’t call the trait’s code for the same method; put the shared part in a method of its own that both use.

Defaults

A trait’s method can have defaults for its last parameters, as a function can. A call through the trait may leave them out, and gets the trait’s defaults. Each obj that is the trait writes the same defaults in its method, so a call on the obj directly means the same:

trait Greeter {
    fn greet(name: str, greeting: str = "Hello"): str
}
obj Plain: Greeter {
    fn greet(name: str, greeting: str = "Hello"): str => "${greeting}, ${name}"
}
g: Greeter = Plain {}
print(g.greet("Ann"))
print(g.greet("Bob", "Hi"))

Output:

Hello, Ann
Hi, Bob

An obj whose method has another default, or none, is an error that shows the trait’s header: Plain is a Greeter, so its method greet must be fn greet(name: str, greeting: str = "Hello"): str, as the trait says.

Which obj it is

is tells whether a trait value holds an object of an obj type. Inside if s is Circle { ... }, s is a Circle: its fields and other methods can be used.

trait Shape {
    fn area(): float
}
obj Circle: Shape {
    r: float
    fn area(): float => 3.0 * self.r * self.r
}
obj Rect: Shape {
    w: float
    h: float
    fn area(): float => self.w * self.h
}

shapes: [Shape] = [Circle{r: 2.0}, Rect{w: 3.0, h: 4.0}]
shapes.walk(s) {
    if s is Circle {
        print("a circle of radius ${s.r}")
    } else {
        print("something of area ${s.area()}")
    }
}

fn describe(s: Shape): str {
    match s {
        Circle { return "round, radius ${s.r}" }
        Rect { return "${s.w} by ${s.h}" }
    }
    return ""
}
print(describe(shapes[1]))

Output:

a circle of radius 2.0
something of area 12.0
3.0 by 4.0
  • Where it is known: in the if (in else after if !(s is Circle)), on the right of && (s is Rect && s.w > 1.0), and in the rest of a block after if !(s is Circle) { return }. As with optional values, it ends where the variable is given another value.
  • Only an obj type that is the trait: s is Dog is an error when Dog isn’t a Shape: it could never be true.
  • One value at a time: it works on a variable or parameter; for a field or an element, put it in a variable first.

describe uses match to go through the obj types. Each case is an obj type that is the trait, at most once (Rect, Square { ... } takes several), and the value is that type in its case. Without else, every obj type that is the trait needs a case: when one is added, the compiler says which match is missing it.

Details

  • trait is a reserved word. A trait is declared at the top level of a file and can be used anywhere in it, also before the declaration.
  • A trait has methods only, no fields. When code needs a value, the trait asks for it with a method, like fn name(): str.
  • A method of a trait can’t be init. One without code can’t be used as a function value (Shape.area), as it has no code of its own; Circle.area can.
  • An obj’s own type stays as it is: c: Circle still has all of Circle’s fields and methods. It becomes a Shape where a Shape is expected.
  • Calling a method through a trait finds the object’s own method when the program runs. It costs a little more than calling it on the obj type directly, about as much as an interface call in Go.

Not available yet

  • Traits that include other traits (trait ReadWriter: Reader, Writer).
  • Traits for the built-in types (int, str, …) and generic traits.
  • Converting trait values to and from JSON.

See Limitations.