Subject: | lexical_has and default values |
"lexical_has" doesn't seem to work properly when the until the attribute has had its value set by a public/external accessor. Default values that have been set by the class definition can't be used.
The issue can be see when testing the code example that is part of the Moops introduction/tutorial:
use Moops;
class Car {
lexical_has max_speed => (
is => 'rw',
isa => Int,
default => 90,
accessor => \(my $max_speed),
lazy => 1,
);
has fuel => (
is => 'rw',
isa => Int,
);
has speed => (
is => 'rw',
isa => Int,
trigger => method ($new, $old?) {
confess "Cannot travel at a speed $new; too fast"
if $new > $self->$max_speed;
},
);
method get_top_speed() {
return $self->$max_speed;
}
}
my $solarcharged = Car->new ;
# This won't compile due to $max_speed scoping:
# say $solarcharged->$max_speed;
# shows expected error "too fast"
$solarcharged->speed(140);
# prints nothing - wrong behavior?
say $solarcharged->get_top_speed();
The issue stems from a question asked here:
http://stackoverflow.com/questions/27558976/moops-lexical-has-and-default-values
As Amon comments on that page the error is not specific to Moops. Amon also posted the following minimal test case with the comment:
perl -E 'package A { use Moo; use Lexical::Accessor; lexical_has attr => (accessor => \my $attr, default => sub { 90 }); sub get { shift()->$attr } }; say A->new->get() // "undef"'
This does not print the default value.