Classes
A class describes something you can make instances of: the data each one holds, and what it can do.
class Lamp
let lamp = Lamp()
Constructor parameters as fields
Marking a constructor parameter with let or var makes it a field, fixed or settable. This is the most common way to
write a class:
class Person(
let firstName: string,
let lastName: string,
var age: i32
) {
let sayHello() {
println("Hello ${firstName} ${lastName}")
}
}
entrypoint main() {
let person = Person("Ada", "Lovelace", 36)
person.sayHello()
person.age = 37
}
A parameter without let or var is passed to the constructor and not kept.
Writing the constructor
Reach for the inline constructor first. Its parameters sit in the class's header, and a field worked out from them is written where the field is declared, with no constructor body at all:
class Rectangle(let width: i32, let height: i32) {
let area = width * height
}
When building an instance takes more than an expression for each field, write the constructor yourself with new. Its
body runs like any function's, so it can decide what each field holds. Here a requested speed is kept between -100 and
100:
class Speed {
let percent : i32
new(requested: i32) {
if (requested > 100) {
percent = 100
} elif (requested < -100) {
percent = -100
} else {
percent = requested
}
}
}
Members
A class's members are its bindings: its fields and its functions. Inside the class they're read by name, or through
self. Outside, through an instance:
class Counter {
var count = 0
let increment() {
count = count + 1
}
}
entrypoint main() {
let counter = Counter()
counter.increment()
println("${counter.count}")
}
private keeps a member inside its class, and static makes a member belong to the class rather than to each
instance.
Traits, not inheritance
A class can implement traits, written after a colon, which is how types share a contract. A class inheriting from another class is not in V0 yet.