Search code examples
perloopmoose

Perl Moose parent class cast with child


package Point;
use Moose;

has 'x' => (isa => 'Int', is => 'rw');
has 'y' => (isa => 'Int', is => 'rw');

package Point3D;
use Moose;

extends 'Point';

has 'z' => (isa => 'Int', is => 'rw');

package main;

use Data::Dumper;

my $point1 = Point->new(x => 5, y => 7);
my $point3d = Point3D->new(z => -5);

$point3d = $point1;
print Dumper($point3d);

Is it possible to cast a parent to child class such as c++? In my examble is $point3d now a Point and not a Point3D include the Point.


Solution

  • Take a look at the Class::MOP documentation on CPAN, especially the clone_object and rebless_instance methods:

    sub to_3d {
      my ($self, %args) = @_;
      return Point3D->meta->rebless_instance(
        $self->meta->clone_object($self),
        %args,
      );
    }
    

    And then use it like the following:

    my $point_3d = $point->to_3d(z => 7);
    

    This will also take care to treat the newly specified %args as if they've been passed in by the constructor. E.g. builders, defaults, and type constraints are all considered during this build.