Classes

Classes add constructors, field defaults, and single inheritance on top of the struct/impl model.

Summary

The constructor method is always named init. Instantiate with ClassName(args). Fields can have defaults declared directly in the class body. Inheritance uses class Dog : Animal; subclasses call super.init(...)to initialize parent fields. Methods can be overridden. Classes and structs/impl coexist in XS; use structs when you don't need inheritance.

Canonical

Classes support constructors, methods, fields with defaults, and single inheritance.

class Animal {
    name = ""
    sound = "..."

    fn init(self, name) {
        self.name = name
    }

    fn speak(self) {
        return "{self.name} says {self.sound}"
    }
}

let cat = Animal("Cat")
cat.sound = "meow"
println(cat.speak())             -- Cat says meow

The constructor method is init. Instantiate with ClassName(args).

Inheritance

class Dog : Animal {
    fn init(self, name) {
        super.init(name)
        self.sound = "woof"
    }

    fn fetch(self) {
        return "{self.name} fetches the ball"
    }
}

let d = Dog("Rex")
println(d.speak())               -- Rex says woof
println(d.fetch())               -- Rex fetches the ball

Subclasses call super.init(...) to initialize parent fields. Methods can be overridden.

Fields with Defaults

class Config {
    host = "localhost"
    port = 8080
    debug = false

    fn init(self, host, port) {
        self.host = host
        self.port = port
    }

    fn url(self) { return "{self.host}:{self.port}" }
}

let c = Config("example.com", 443)
println(c.url())                 -- example.com:443
println(c.debug)                 -- false