Skip to content

Instantly share code, notes, and snippets.

@moritz
Created September 26, 2015 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save moritz/5cda6371ab3cfec3254e to your computer and use it in GitHub Desktop.
Save moritz/5cda6371ab3cfec3254e 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 () { $!varies },
STORE => method ($new) { $!varies = $new + 1 },
);
}
}
my $mv = MagicVal.new(:constant(6), :varies(6));
say $mv.varies.VAR.^name; # Proxy
say $mv.varies.^name; # Method
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment