Skip to content

Methods and Properties

Chloë Strainge edited this page Oct 15, 2026 · 2 revisions

Methods and properties

Declare an extension method as fn TypeName::method(...). An ordinary method gets an implicit live $self receiver. Zero-argument methods run on property-style access; methods with arguments use spaces.

fn Integer::increase($amount: Integer): Integer
{
    $self = $self + $amount
    $self
}
let $score = 10
let $raise = `$score.increase
echo ($raise 5) $score
15 15

The reference keeps the original binding, not a copied receiver. It also keeps the method version selected when it was created. Writing $self enforces that binding's constraints. A receiver expression that is not a variable uses a temporary value.

Use .method, not .method(), for a no-argument method. The latter supplies a unit argument. any::method can provide behavior across types, with more specific methods selected through normal method resolution.

Methods follow the function return rules: no result annotation means (). Mutating $self does not require returning it; declare : any or a concrete result type when a method also returns a value.

Computed properties

get_name supplies readable .name; set_name supplies writable .name. Inside the implementation .::name accesses raw storage without recursively calling the accessor. A setter can validate the value before changing storage. Structs gives a complete constructor/accessor example.

Dynamic access uses $object.$member or $object.::$member. The member name must be a String. Interpolation supports braced member paths with these rules too.

Collection-dependent contracts

fn Array::first_or_none(): $self.value_type | ()
{
    if $self.count == 0 { return () }
    let $item: $self.value_type = $self[0]
    $item
}
let $readings: [Float] = [3, 4]
echo $readings.first_or_none $readings.first_or_none.type
3.0 Float

Array methods can refer to $self.value_type in parameters, results, and locals. Hash methods can also use $self.key_type. Contracts specialize to the receiver; known incompatible uses can be checked before execution, and dynamic values are validated at runtime. They are not general expressions allowed in arbitrary type positions: a compatible collection method receiver is required.

Methods follow module privacy. Mark an exported extension pub; importing its module activates its public extensions even with a selective import.


Related: Structs · Conversions · Reflection

Clone this wiki locally