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

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

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

Problem:  

You want to declare an attribute of a class.

Solution:  

Use the has keyword:

class MyClass {
    has int $.counter;
    has $.max = 100;
}

Discussion:

Attributes of a class are created using a syntax almost identical to that used to create variables in packages. You optionally may specify the the, properties, and initial value for the attribute: the "initial value" is the value that the attribute will be initially set to in every new instance of the class.

See the next recipe for tips on how to access attributes once you've created them.

Issue: Is the sigil optional, if it can be inferred from the type?

Issue: Is the '.' optional, since it is redundant w/ 'has'?

Issue: Maybe an optional 'strict'ness to enforce that every attribute must be declared with a type?


Log In to Comment


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