Skip to content

Classes

Classes are reference types allocated with new:

class Counter {
priv value: Int;
fun init(value: Int) {
self.value = value;
}
pub fun increment() Int {
self.value = self.value + 1;
return self.value;
}
}
var counter = new Counter(0);
println(toString(counter.increment()));

init is the constructor. Instance methods receive self implicitly.

Copying a class value copies the managed reference, not the object:

var first = new Counter(0);
var second = first;
second.increment();
println(toString(first.increment()));

Both variables refer to the same counter.

Class members are private unless marked otherwise:

ModifierAccess
privThe declaring class
protThe declaring class and its subclasses
pubAny caller that can access the class

Keep mutable fields private when methods can enforce a useful invariant.

A static method belongs to the class and does not receive self:

class Ids {
pub static fun first() Int {
return 1;
}
}
var id = Ids.first();

Define deinit for deterministic cleanup when an acyclic object’s final strong reference is released:

class FileLease {
fun deinit() {
println("lease released");
}
}

The object itself remains managed by Zap. See Ownership and ARC for release and cycle semantics.

Use a class for identity, shared mutable state, or polymorphic behavior. Use a record or struct for value data.

Subclassing and dynamic dispatch are covered in Inheritance.