I'm trying to implement a Moose::Role class that behaves like an abstract class would in Java. I'd like to implement some methods in the Role, but then have the ability to override those methods in concrete classes. If I try this using the same style that works when I extend classes I get the error Cannot add an override method if a local method is already present
. Here's an example:
My abstract class:
package AbstractClass;
use Moose::Role;
sub my_ac_sub {
my $self = shift;
print "In AbstractClass!\n";
return;
}
1;
My concrete class:
package Class;
use Moose;
with 'AbstractClass';
override 'my_ac_sub' => sub {
my $self = shift;
super;
print "In Class!\n";
return;
};
__PACKAGE__->meta->make_immutable;
1;
And then:
use Class;
my $class = Class->new;
$class->my_ac_sub;
Am I doing something wrong? Is what I'm trying to accomplish supposed to be done a different way? Is what I'm trying to do not supposed to be done at all?
requires 'my_ac_sub';
in the Role, not the "virtual" method. Moose::Role will then check it has been composed into a class with the method available, – Offenbachsub my_ac_sub
and suddenly it worked just as expected. Is there anything wrong with that "fix"? (Disclaimer: I'm new to Moose). – Varietalsuper()
part. But then, roles don't get into@ISA
anyway andsuper
seems to use that... As I understand, "not allowing to be created" can be achieved bybefore "new" => sub { $_[0] eq __PACKAGE__ and die "Abstract" };
, but that's a hack and there must be something better. – Varietal