Mixed object variables available in a mixed-mode role declaration

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?

+5
source share
1 answer

The correct syntax will be $.word , which is basically abbreviated for self.word , so it uses a public access method.

But I think there are some typos and some misconceptions. The typo (I think) is that .bless only accepts named parameters, so instead of $word it should be :$word (turn positional by word => $word ). In addition, a role that defines but does not implement a method and then uses the same name to implement a role with this name does not make sense. And I am surprised that this does not cause an error. So get rid of this for now. This is my decision":

 class Bare-Word { has $.word; method new ( Str $word ) { return self.bless( :$word ); # note, .bless only takes nameds } } my $that-word = Bare-Word.new( "Hola" ) but role jsonable { method to-json() { return "['$.word']"; # note, $.word instead of $!word } } dd $that-word; # Bare-Word+{jsonable}.new(word => "Hola") 

Hope this helps.

+6
source

Source: https://habr.com/ru/post/1274539/


All Articles