Perl6 Object Oriented Cookbook (v0.2.1)  
Section 4: Inheritance  
 
Recipe 4.3: Inheriting from Literal Values
Last Updated: Sep 8, 2003
Status: Draft
      Previous Page   Next Page

How important is this problem to you?
  (Login to Vote)
4.00 Rating, 3 Votes  

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

Problem:  

You want your class to inherit from a literal value.

Solution:  

Just do it:

class WombatString is "wombat";  # note the quotes!

class ZeroButTrue is 0 {         # OO version of "0 but true"
    as boolean 1;
}

Discussion:

In the second example above, we have declared a class, ZeroButTrue, that inherits from the literal value 0. Then we've declared a transformation (See Section 5) which specifies that when this object is evaluated in boolean context, it should return the literal value 1, e.g. "true".

This can be an extremely powerful way to quickly make classes that are treated as literal (constant) values in almost all situations, but that have extra methods or transformations that the original value didn't.

When inheriting from a literal value, you are inheriting from an instance of whatever builtin type that literal value represents. See Section 6 to learn what builtin types exist in perl, and how to subclass those builtin types.


Log In to Comment


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