Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare a class attribute as a union of class names?

Tags:

raku

I'm reading a spreadsheet looking for different structures. When I tried the following using Moose it seems to do what I want. I could create different types of objects, assign this to the found member and dump the Cell instance for review.

package Cell
{
  use Moose;
  use Moose::Util::TypeConstraints;
  use namespace::autoclean;

  has 'str_val'    => ( is => 'ro', isa => 'Str', required => 1 );
  has 'x_id'       => ( is => 'ro', isa => 'Str', ); # later required => 1 );
  has 'color'      => ( is => 'ro', isa => 'Str', );
  has 'border'     => ( is => 'ro', isa => 'Str', );
  has 'found'      => ( is => 'rw', isa => 'Sch_Symbol|Chip_Symbol|Net', );
  1;
}

If I try to do the same in Perl 6 it fails to compile.

class Cell {
  has Str $.str_val              is required;
  has Str $.x_id                 is required;
  has Str $.color;
  has Str $.border;
  has Sch_Symbol|Chip_Symbol|Net $.found is rw
}
Malformed has
at C:\Users\Johan\Documents/moose_sch_3.pl6:38
------>   has Sch_Symbol'<'HERE'>'|Chip_Symbol|Net $.found is rw

How can I do this in Perl 6?

like image 543
WindWhizzler Avatar asked Apr 04 '18 21:04

WindWhizzler


1 Answers

You probably want them to do a common role and specify that as the type

role Common {}
class Sch-Symbol does Common {…}
…

class Cell {
  …
  has Common $.found is rw;
}

Or you will have to use a where constraint

class Cell {
  …
  has $.found is rw where Sch-Symbol|Chip-Symbol|Net;
}

You could also create a subset to wrap the where constraint.

subset Common of Any where Sch-Symbol|Chip-Symbol|Net;

class Cell {
  …
  has Common $.found is rw;
}

Note that a where constraint is slower than using a common role.

like image 67
Brad Gilbert Avatar answered Sep 19 '22 15:09

Brad Gilbert