Perl6 Object Oriented Cookbook (v0.2.1)  
Section 1: Introduction to Object Oriented Perl6  
 
Recipe 1.10: Using Objects as Classes
Last Updated: Sep 8, 2003
Status: Very Likely
      Previous Page   Next Page

How important is this problem to you?
  (Login to Vote)
4.50 Rating, 4 Votes  

How acceptable is the proposed solution?
  (Login to Vote)
5.00 Rating, 4 Votes  

Problem:  

You want to use an object as if it were a Class. For example, you want to use CAN or HAS on an object, even though they are technically class methods, not instance methods.

Solution:  

Just do it:

$obj.CAN;

Discussion:

An object is, by definition, nothing more than a specific instance of a builtin type or class. You may call class methods within an object just as you would call any other method: when the method is called, it will use the class of the object, and instance information will be unavailable.

In perl5, the first argument to a method was either a class name or an object instance, depending on how the method had been called. This led to code like:

sub foo {
    my $type = shift;
    $type = ref $type if ref $type;		# make sure it's a class name
    
    ...
}
For class methods in perl6, the step of converting an object to a class name is done automatically when you call a class method on an object instance.


Log In to Comment


Login / Edit User Info -- Copyright © 2002 Cognitivity -- Previous Page   Next Page