Skip to content

Instantly share code, notes, and snippets.

@lucs
Last active January 19, 2022 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucs/387b10ac9576bf9a04fcdfdb12ce91d0 to your computer and use it in GitHub Desktop.
Save lucs/387b10ac9576bf9a04fcdfdb12ce91d0 to your computer and use it in GitHub Desktop.
Raku constructor question
# Close, in the sense that class B has no idea of the implementation
# of some-A-method, but B.new returns the wrong type of instance.
class A {
has $.a;
method new ($x) {
return self.bless: :a($x / 2);
}
method some-A-method {
return $!a;
}
}
class B is A {
has $.b = 66;
method new ($x) {
A.new($x);
}
}
my $b = B.new(42);
# Expecting 21.
say $b.some-A-method;
# Expecting 66.
say $b.b;
@lucs
Copy link
Author

lucs commented Jan 18, 2022

Thanks for your response. Turns out I had not explained precisely enough what I was after (it even became clear to me only as we went back and forth discussing it on IRC (raku channel on libera). The following solution (fixed up a bit by me), the thing I was after (class B knowing nothing of class A's implementation), was proposed by gfldex:

class A {
    has $!a;

    submethod TWEAK {
        $!a = $*x;
    }

    method some-A-method {
        return $!a / 2;
    }
}

class B is A {

    method new ($*x) { 
        self.bless;
    }
}

say B.new(42).some-A-method;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment