Immutability
Immutable Variables
The immut keyword prevents reassignment:
immut int x = 42;// x = 10; // ERROR: cannot assign to immutable variable
immut Point p = Point(10, 20);// p.x = 5; // ERROR: cannot modify immutable valueImmut Methods
Methods marked immut guarantee they will not modify the object (except mutable fields):
type Counter{ int value; mutable int cache;
int GetValue() immut { return this.value; }
int GetCached() immut { this.cache = this.value * 2; // OK: cache is mutable return this.cache; }
void Increment() { this.value = this.value + 1; }}Immut Receivers
An immut variable can only call immut methods:
Counter c = Counter();c.GetValue(); // OKc.Increment(); // OK
immut Counter ic = c;ic.GetValue(); // OK// ic.Increment(); // ERROR: Increment is not immutMutable Fields
Fields marked mutable can be modified even in immut methods. This is useful for caches, lazy-computed values, and diagnostics:
type Data{ int value; mutable int accessCount;
int Get() immut { this.accessCount = this.accessCount + 1; return this.value; }}Dual-Mode with immut?
The immut? modifier serves two purposes: it allows a method to be called from both mutable and immutable contexts, and it propagates the receiver’s immutability to the return type.
On Methods
A method marked immut? can be called on both mutable and immutable objects:
type Data{ int value; int GetValue() immut? { return this.value; }}
Data d = Data();immut Data id = d;d.GetValue(); // OK: mutable contextid.GetValue(); // OK: immutable contextOn Return Types
When immut? appears on the return type, the returned value inherits the immutability of the object it was called on:
type Container{ OtherType item;
immut? OtherType GetItem() immut? { return this.item; }}
Container c = Container();immut Container ic = c;
c.GetItem(); // returns OtherType (mutable)ic.GetItem(); // returns immut OtherType (immutable)The immut? on the return type means: “return immut OtherType when called through an immutable object, and OtherType when called through a mutable object.” This lets a single method definition safely expose internal data without breaking immutability guarantees.
in Parameters
in is syntactic sugar for immut ref — an immutable by-reference parameter:
int Sum(in Point p){ return p.x + p.y; // read-only access // p.x = 10; // ERROR: cannot modify}This is equivalent to immut ref Point p but more concise. in is only valid as a parameter modifier.