docs / Getting Started / Traits

Traits

Traits define shared interfaces — a set of abstract and optionally concrete method signatures that classes can implement. Traits support inheritance and default methods.

use system.io

trait Logger
    fn prefix() String
        "INFO"                     // default implementation

    fn log(msg String)
        println(f"[{self.prefix()}] {msg}")

class AppLogger implements Logger
    fn prefix() String
        "APP"                      // override default

fn main()
    let logger = AppLogger()
    logger.log("started")          // [APP] started

Key concepts

  • implements — Attach one or more traits to a class. The class must provide implementations for all abstract methods.
  • Default methods — Traits can provide method bodies. Classes inherit the default unless they override it.
  • Trait inheritance — Traits can extend other traits with extends. Implementing a derived trait requires implementing the entire chain.
  • Multiple traits — A class can implement multiple traits: class X implements A, B.
  • Combined — A class can extend a base class and implement traits: class Fish extends Animal implements Swimmer.
  • Self type — Use Self in trait signatures to refer to the implementing class's own type.