Skip to content

Instantly share code, notes, and snippets.

@lizmat
Created February 5, 2017 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lizmat/a98b5115f624416a3a0534b12c9469d4 to your computer and use it in GitHub Desktop.
Save lizmat/a98b5115f624416a3a0534b12c9469d4 to your computer and use it in GitHub Desktop.
prototype for an "is write-once" trait for Attributes
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