In Moose, how to specify constructor arguments for the superclass in a subclass?

123 views Asked by At

I have a Moose class with some properties (x,y,z). I subclass it, and for the subclass, x is always 3. How can I specify this in subclass?

2

There are 2 answers

0
ikegami On BEST ANSWER

One could use BUILDARGS.

around BUILDARGS => sub {
    my $orig  = shift;
    my $class = shift;
 
    return $class->$orig(@_, x => 3 );
};
1
Joel On

I used to work with Moo but it seems to be the same. You just need to declare the property in the subclass using + to override previous declaration.

package Foo;
use Moose;
 
has 'a' => (
    is => 'rw',
    isa => 'Num',
);

has 'b' => (
    is => 'rw',
    isa => 'Num',
);

has 'c' => (
    is => 'rw',
    isa => 'Num',
);


package My::Foo;
use Moose;
 
extends 'Foo';
 
has '+a' => (
    default => 3,
);