Skip to content

Instantly share code, notes, and snippets.

@peschwa
Forked from moritz/t-spec-S12-attributes-mutators.t
Last active September 26, 2015 13:39
Show Gist options
  • Save peschwa/d1a11ea4e61f9d9d6a0e to your computer and use it in GitHub Desktop.
Save peschwa/d1a11ea4e61f9d9d6a0e to your computer and use it in GitHub Desktop.
Proxy surprise
our $count = 0;
class MagicVal {
has Int $.constant;
has Int $.varies = 0;
method varies is rw {
$count++;
return-rw Proxy.new(
# note that FETCH and STORE cannot go through the accessors
# of $.varies again, because that would lead to infinite
# recursion. Use the actual attribute here instead
FETCH => method ($fles:) { $fles.varies },
STORE => method ($fles: $new) { $fles.varies = $new + 1 },
);
}
}
my $mv = MagicVal.new(:constant(6), :varies(6));
say $mv.varies.VAR.^name; # Proxy
say $mv.varies.^name; # Method
say $mv.varies;
$mv.varies = 5;
say $mv.varies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment