Perl6 Object Oriented Cookbook (v0.2.1)  
Section 2: Attributes and Methods  
 
Recipe 2.7: Creating 'Class Methods'
Last Updated: Sep 8, 2003
Status: Unlikely
      Previous Page   Next Page

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

How acceptable is the proposed solution?
  (Login to Vote)
3.50 Rating, 2 Votes  

Problem:  

You want to create a class method: a method that may be called using the class name explicitly, and that does not require an instance to be created in order for the method to be used.

Solution:  

Declare the method using the is classwide property:

method do_something is classwide { ... };

Discussion:

A class method is a generic term for a method of a class may be called without actually creating an instance of the class. You may call class methods within an object just as you would call any other method, but when the method is called, it will use the class of the object, and instance information will be unavailable.

When creating methods 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. To mimic the effect of class methods, code like this was often used:

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

Issue: Desperately needs a better property name.

Issue: Or, we just use sub to declare class methods... but that doesn't solve the problem of first-argument blues, unless we special-case it.


Log In to Comment


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