Object Construction
Public constructor (default: named arguments only) → calls bless Creates the object → calls BUILDALL BUILD (submethod)
Initialize attributes from named args (replaces default initialization) Applied for attributes not set by BUILD TWEAK (submethod)
Post-initialization adjustments and validation (preferred over BUILD)
Submethods aren't inherited (so each class in the hierarchy gets its own BUILD/TWEAK).
Attribute traits: is required, is rw, is default(...), is built (allow a private attribute to be set by new: has $!secret is built;), is built(False).
class Point {
has Numeric $.x = 0;
has Numeric $.y = 0;
# Positional constructor (new only accepts named args by default)
multi method new(Numeric $x, Numeric $y) { self.bless(:$x, :$y) }
submethod BUILD(:$!x = 0, :$!y = 0) { } # optional: customize attribute initialization
submethod TWEAK { # validate/adjust after attributes are set
die "Coordinates must be finite" unless $!x.abs < Inf && $!y.abs < Inf;
}
method distance-to(Point $p --> Numeric) { sqrt(($!x - $p.x)² + ($!y - $p.y)²) }
method gist { "Point($!x, $!y)" }
}
my $p1 = Point.new(x => 3, y => 4);
my $p2 = Point.new(0, 0); # positional multi new
say $p1.distance-to($p2); # 5
say $p1.clone(y => 10); # Point(3, 10): shallow copy with changes