'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?



Solution 1:[1]

One could use BUILDARGS.

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

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ikegami
Solution 2 Joel