develooper Front page | perl.perl6.users | Postings from January 2020

weirdness with subset on has

Thread Next
From:
Joseph Brenner
Date:
January 13, 2020 01:09
Subject:
weirdness with subset on has
Message ID:
CAFfgvXWjapjKea8odVtm8-8DsSCG0a4m835ANwCf3PXFMHjceQ@mail.gmail.com
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")

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About