Created
February 5, 2017 13:11
-
-
Save lizmat/a98b5115f624416a3a0534b12c9469d4 to your computer and use it in GitHub Desktop.
prototype for an "is write-once" trait for Attributes
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
use MONKEY; | |
sub trait_mod:<is>(Attribute:D $attr, :$write-once!) { | |
my $class := nqp::getattr($attr,Attribute,'$!package'); | |
my str $name = nqp::getattr($attr,Attribute,'$!name'); | |
my $type := nqp::getattr($attr,Attribute,'$!container_descriptor').default; | |
$class.^add_method( | |
nqp::substr($name,2), | |
my method () is rw { | |
nqp::if( | |
nqp::eqaddr(nqp::decont(nqp::getattr(self,$class,$name)),$type), | |
nqp::getattr(self,$class,$name), | |
nqp::decont(nqp::getattr(self,$class,$name)) | |
) | |
} | |
) | |
} | |
class A { | |
has Int $!a is write-once; | |
} | |
my $a = A.new; | |
dd $a.a; | |
$a.a = 42; | |
dd $a.a; | |
$a.a = 666; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment