Perl6 Object Oriented Cookbook (v0.2.1)  
Section 6: Context and Transformation  
 
Recipe 6.1: Making a Class Context-Aware
Last Updated: Sep 8, 2003
Status: Draft
      Previous Page   Next Page

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

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

Problem:  

You want to allow instances of your class to return different values in different contexts.

Solution:  

Use as to define contextual transformations:

class MyClass {
    as boolean      1;        # a literal value
    as integer      1;        # a literal value
    as string       { ... };  # an anonymous method
    as AnotherClass { ... };  # an anonymous method
}

my $obj = MyClass.new;        # create the class

print('OK') if $obj;          # uses the 'boolean' transformation
print($obj+1);                # uses the 'integer' transformation
print $obj;                   # uses the 'string' transformation
print($obj as AnotherClass);  # uses the 'AnotherClass' transformation

Discussion:

The as keyword defines contextual transformations of an object. In other words, it defines what instances of your class will return when called in a particular named context.

In the declaration form, shown above, as takes two arguments; the context or contexts being declared, and a literal value or anonymous method that will translate the object in that context. You don't have to define every possible context: perl will look for the 'closest' match, and use that.

The operator form of as, shown in the last line of the example, allows you to force a particular context upon the object.

The most common use of as is to define an object's behavior in the "builtin" contexts (scalar, list, hash, etc.), but it also capable of converting an instance of the class to any other arbitrary type, so long as the transformations have been defined.


Log In to Comment


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