I was wondering how to mix an abstract role with a variable at runtime. Here is what I came up with
role jsonable { method to-json( ) { ... } } class Bare-Word { has $.word; method new ( Str $word ) { return self.bless( $word ); } } my $that-word = Bare-Word.new( "Hola" ) but role jsonable { method to-json() { return "['$!word']"; } };
However, this causes a (perfectly reasonable) error:
$ perl6 role-fails.p6 ===SORRY!=== Error while compiling /home/jmerelo/Code/perl6/dev.to-code/perl6/role-fails.p6 Attribute $!word not declared in role jsonable at /home/jmerelo/Code/perl6/dev.to-code/perl6/role-fails.p6:14 ------> hod to-json() { return "['$!word']"; } }⏏; expecting any of: horizontal whitespace postfix statement end statement modifier statement modifier loop
$!word belongs to the class, so it is not available as such in the mixin declaration. However, but just a function call , so the declared variable must be accessible internally, right? What will be the correct syntax for accessing it?
source share