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

Time:03-27

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?

CodePudding user response:

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,
);

CodePudding user response:

One could use BUILDARGS.

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