Anna
Anna

Reputation: 2845

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

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?

Upvotes: 2

Views: 136

Answers (2)

ikegami
ikegami

Reputation: 385897

One could use BUILDARGS.

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

Upvotes: 3

Joel
Joel

Reputation: 1239

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

Upvotes: 3

Related Questions