Moving the definition of the subset outside of the class
covers for the weird behavior...
my @allowed = << alpha beta gamma delta >>;
my @default = << alpha >>;
subset Allowed of Str where * eq any( @allowed );
class HasSubset {
has Allowed @.grk = @default;
method echo_grk {
say @!grk.join(" | ");
}
}
my $obj = HasSubset.new();
$obj.echo_grk();
my $obj2 = HasSubset.new( grk => << alpha beta gamma >> );
$obj2.echo_grk();
my $obj3 = HasSubset.new( grk => << alpha beta rutabaga >> );
$obj3.echo_grk();
# value 'rutabaga' fails as expected:
# Type check failed in assignment to @!grk; expected
HasSubset::Allowed but got Str ("rutabaga")
On 1/12/20, Joseph Brenner <[email protected]> wrote:
> Here's a code snippet that tries to use a subset to constrain the
> values of an object field (i.e. declared with has). As written, this
> code works, but only when there's what looks like an irrelevant
> experimental line in it (labeled "WEIRD ONE"), when that line is
> commented out it throws an error...
>
> class HasSubset {
> my @allowed = << alpha beta gamma delta >>;
> my @default = << alpha >>;
>
> subset Allowed of Str where * eq any( @allowed );
>
> my Allowed $experiment = 'delta'; # WEIRD ONE this line is
> *needed* to get the following to work...
>
> has Allowed @.greek = @default;
>
> method echo_greek {
> say @!greek.join(" | ");
> }
> }
>
> my $obj = HasSubset.new();
> $obj.echo_greek();
>
> # As written, prints the default: 'alpha'
> # Without the WEIRD ONE line, you see errors like:
> ## Type check failed in assignment to @!greek; expected
> HasSubset::Allowed but got Str ("alpha")
>