Skip to content

Classes

Zap supports heap-only class types allocated with new.

class Counter {
priv value: Int;
fun init(value: Int) {
self.value = value;
}
pub fun inc(step: Int) Int {
self.value = self.value + step;
return self.value;
}
}
var counter: Counter = new Counter(10);

init(...) acts as the initializer. self is available inside instance methods.

Visibility modifiers:

  • pub
  • priv
  • prot

Single inheritance is supported:

class Base {
pub fun value() Int {
return 1;
}
}
class Derived : Base {
pub fun value() Int {
return 2;
}
}

Methods dispatch dynamically through the base type.

class Task {
prot done: Bool;
fun init() {
self.done = false;
}
pub fun finish() {
self.done = true;
}
}

Classes can define:

  • init(...) for initialization
  • deinit() for cleanup on final release

Weak references and ARC details are covered in ARC and weak refs.