Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the "has" keyword mean before "method" in a Raku class definition?

Tags:

syntax

raku

Recently I realised that I had written, entirely by mistake, one of my Raku classes like this:

class Foo {
  has method bar {
    return 'some string';
  }
}

I was surprised to realise that the has method was not an error, and worked as expected.

What is the has doing in this case? Is this an intentional behaviour?

like image 863
jja Avatar asked Sep 21 '20 19:09

jja


1 Answers

has is a scope declarator, in the same category as things like my, our, state, and anon. Something that is has-scoped is installed in the meta-class of the current package.

Variable-like things are always declared with an explicit scope, for example:

my $lexical-var;
my $.lexical-var-with-accessor;
has $!attribute;
has $.attribute-with-accessor;

Many other constructs can optionally have their scope specified, but come with a sensible default. For example:

  • my sub marine() { } - the same as without the my
  • our class Struggle { } - the same as without the our
  • has method in-the-madness() { } - the same as without the has

The most common alternative scope for methods is probably anon, which is useful when meta-programming. For example, if we are writing a class that is going to construct another class using the MOP, we may write:

$the-class.^add_method('name', anon method name() { $name });

Which means we don't end up with the method name being installed on the current class we're in. Most of the time, however, we want has scope. It does no harm to specify it explicitly, just as it does no harm to write my before sub; it's just reaffirming a default.

like image 153
Jonathan Worthington Avatar answered Oct 13 '22 18:10

Jonathan Worthington