Authoritative source: Classes and objects

Classes and objects

Classes provide nominal identity, fields, construction, and dynamic method dispatch. They are a first-class language concept, not syntax sugar for records or algebra dictionaries.

Declaring a class

class Animal(name:String, age:Int) = {
    function describe(self:Self) : String = self.name
};

Constructor parameters are fields. Instance methods take an explicit self; Self is preferred when a method participates in inheritance.

Construction and calls

value animal = Animal.new("Milo", 4);
value name = animal.name;
value text = animal.describe();

Method syntax inserts the receiver as self. Field access remains ordinary dot projection.

Static methods

static function family() : String = "Animalia"

A static method has no receiver. It belongs to class organization without participating in dynamic dispatch.

Abstract and sealed classes

abstract class Shape = {
    function area(self:Self) : Float64
};

sealed class Result(a:Type) = { ... };

Abstract classes cannot be constructed directly. A sealed class can only be subclassed in its defining module, enabling exhaustive matching over known children.

Implementing algebras

class User(name:String) implements Show(User), Eq(User) = { ... };

implements constructs ordinary algebra evidence from matching methods or derivation logic. Class inheritance and algebra evidence remain distinct.

Classes or algebraic data?

Choose a class for open nominal extension and dynamic method selection. Choose an algebraic data type for a known set of constructors and direct exhaustive matching. Sealed classes deliberately occupy useful middle ground.

Current implementation

Native class construction, fields, selected method dispatch, inheritance, and checked downcasts have reference tests. Future providers may map canonical classes to .NET, JavaScript, or C++ class mechanisms only when they preserve the portable contract.

Common mistakes

Instance methods need an explicit self; static methods do not. Do not use classes as evidence dictionaries or assume an open hierarchy is exhaustively matchable without a fallback.

Recap

Classes provide nominal state and dynamic behavior. Their object hierarchy is separate from structural records and from algebra evidence.

Normative details: Language Reference §12.