4

Yes, still going with this. My impression is that there's this powerful facility in Raku, which is not really easy to use, and there's so little documentation for that. I'd like to kind of mitigate that.

In this case, I'm trying to force attributes to be read-only by default, to make immutable classes. Here's my attempt:

my class MetamodelX::Frozen is Metamodel::ClassHOW {

    method compose_attributes($the-obj, :$compiler_services) {
        my $attribute-container = callsame;
        my $new-container = Perl6::Metamodel::AttributeContainer.new(
                :attributes($attribute-container.attributes),
                :attribute_lookup($attribute-container.attribute_table),
                :0attr_rw_by_default
                );
        $new-container.compose_attributes($the-obj, $compiler_services);
    }
}

my package EXPORTHOW {
    package DECLARE {
        constant frozen = MetamodelX::Frozen;
    }
}

I'm calling that from a main function that looks like this:

use Frozen;

frozen Foo {
    has $.bar;

    method gist() {
        return "→ $!bar";
    }
}

my $foo = Foo.new(:3bar);

say $foo.bar;

$foo.bar(33);

I'm trying to follow the source, that does not really give a lot of facilities to change attribute stuff, so there seems to be no other way that creating a new instance of the container. And that might fail in impredictable ways, and that's what it does:

Type check failed in binding to parameter '$the-obj'; expected Any but got Foo (Foo)
at /home/jmerelo/Code/raku/my-raku-examples/frozen.raku:7

Not clear if this is the first the-obj or the second one, but any way, some help is appreciated.

4
  • I'm slightly confused by the terminology in your question. Attributes already are read-only by default, unless declared with is rw. So I'm guessing you mean something more than that when you say "read only". Do you mean that you want them to be fully immutable, even from within the class? Or something else? Jan 16, 2022 at 14:58
  • They are externally read only, they can still be modified by simply giving them a value. ro mostly indicates the creation of a setter or not.
    – jjmerelo
    Jan 16, 2022 at 17:03
  • 1
    So you only want them to be able to be set at object creation? Not even being able to modify the private value internally? Jan 19, 2022 at 15:32
  • 1
    @ScimonProctor Correct.
    – jjmerelo
    Jan 19, 2022 at 18:40

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.