Perl6 Object Oriented Cookbook (v0.2.1)  
Section 3: Working with Classes  
 
Recipe 3.6: Adding or Changing an Attribute or Method of a Class at Runtime
Last Updated: Sep 8, 2003
Status: Draft
      Previous Page   Next Page

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

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

Problem:  

You want to add an attribute or method to a class, or change the value or implementation of an existing attribute/method, but only under certain (runtime) conditions.

Solution:  

Use code like the following:

class MyClass { ... };     # the original class

MyClass.foo = 5;               # add an attribute
MyClass.bar = method { ... }   # add a method

Discussion:

Perl6 allows you to modify the structure of a class even at runtime, if that class does not specifically forbid it.

There are a number of circumstances in which you may not add an attribute or method to a class, or modify an existing attribute or method. Among them:

  • The class has been declared is final
  • The attribute or method has been declared is final
  • The attribute or method is marked as is interface, and your new value or method does not match the previously defined type or signature.
Each of these circumstances throw the appropriate exceptions.

If you are merely defining a new implementation of a method, but don't want to change the signature of the old method, don't put signature information in the anonymous method constructor:

MyClass.bar = method is prop1, prop2 (... args ...) { ... };  # with signature

MyClass.bar = method { ... };    # uses the existing signature
In addition to being much more compact, the second form makes it much easier to ensure you're really making a method with the signature that's expected. (You don't have to worry about typos, for starters.)

Issue: Or will we be using MyClass.bar := method { ... }?


Log In to Comment


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