David B
David B

Reputation: 29998

What's the order of construction of an extend-ing Moose object class?

I wrote a Moose object class which extends another Moose object class:

package MySubClass;
use Moose;
extends MySuperClass;

I have an attribute which I'd like to automatically build upon object instantiation:

has 'id' => (
    is       => 'ro',
    isa      => 'Str',
    builder  => '_build_id',
    init_arg => undef,
); 

sub _build_id {
 my $self = shift;
 # both ssn and bnn are attributes of MySuperClass
 return $self->ssn . $self->bnn;
}

This doesn't work unless I set id as lazy. Why?

How is the construction of extending objects done?

Upvotes: 2

Views: 235

Answers (1)

zoul
zoul

Reputation: 104065

Quote Moose::Manual::Attributes on Laziness:

First, if the default value for this attribute depends on some other attributes, then the attribute must be lazy. During object construction, defaults are not generated in a predictable order, so you cannot count on some other attribute being populated when generating a default.

Upvotes: 4

Related Questions