Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create Java-like interfaces in Perl?

I understand that Perl's OO model is rather primitive; it is, in most respects, essentially a namespace hack.

Nevertheless, I wonder if it is possible to create something like an "interface?" My goal is to have a base class from which others are extended whose principal purpose is to make mandatory the implementation of certain methods (by name is fine, no signature necessary) by those subclasses. I don't really care if it's a "purely virtual" class (like an "interface" in Java) or a concrete class with actual implementational stubs for those methods in the superclass, but what I want is to make it deterministically necessary that the subclass implement certain methods of the superclass.

Is this possible? If so, how?

like image 352
Alex Balashov Avatar asked Jul 02 '09 04:07

Alex Balashov


1 Answers

Here's an answer using Moose ...

package Comparable;
use Moose::Role;

requires 'eq';

package Person;

has size => (
    is   => 'ro',
    does => 'Comparable',
);

Now the size attribute must be an object which implements the Comparable "interface". In Moose-land, interfaces are roles, and roles can be more than just an interface definition.

like image 82
Dave Rolsky Avatar answered Sep 28 '22 17:09

Dave Rolsky