Is it possible to access static methods and attributes outside the class in Raku?

Viewed 158

In raku it seems possible to define static methods (via sub keyword) and static attributes (via my) Those can be referenced inside the same class.

However, is it possible to access those methods and attributes outside of the class?

Something similar to this:

class MyClass {
    my $attribute = 123;
    sub my-method {
        say 'Hello';
    }
}

MyClass.$attribute;
MyClass.my-method;
1 Answers

it seems possible to define static methods (via sub keyword) and static attributes (via my) Those can be referenced inside the same class.

I can see why you're calling them static methods and attributes but Raku has a much simpler solution for those:

class MyClass {        
    method my-method {
        say 'Hello';
    }
    method attribute is rw {
      state $attribute = 123
    }
}

say MyClass.attribute;   # 123
MyClass.attribute = 99;
say MyClass.attribute;   # 99
MyClass.my-method;       # Hello

You could use our subs and our variables. our is the declarator used to define a lexical that is also for use outside the package it's declared withing. (mys are never shared; a sub declarator without an our is the same as my sub.)

So:

class MyClass {        
    our sub my-sub {
        say 'Hello';
    }
    our $attribute = 123
}
import MyClass;
say $MyClass::attribute;   # 123
$MyClass::attribute = 99;
say $MyClass::attribute;   # 99
MyClass::my-sub;           # Hello

As you can see, these aren't methods; this approach ignores OOP in the sense the prior solution does not.

Related