Created
September 26, 2015 13:31
-
-
Save moritz/5cda6371ab3cfec3254e to your computer and use it in GitHub Desktop.
Proxy surprise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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