Skip to content

Commit 509428b

Browse files
committed
Adds doc on class attributes, closes #2089
1 parent 746819f commit 509428b

File tree

1 file changed

+24
-3
lines changed

1 file changed

+24
-3
lines changed

doc/Language/classtut.pod6

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -142,13 +142,11 @@ You can also use type smileys to only accept instances or type objects:
142142
say foo Int; # OUTPUT: «It's a type object!␤»
143143
say foo 42; # OUTPUT: «It's an instance!␤»
144144
145-
=head1 State
146-
147145
X<|attributes>
148146
X<|classes,attributes>
149-
150147
X<|encapsulation>
151148
X<|classes,encapsulation>
149+
=head1 State
152150
153151
The first three lines inside the class block all declare attributes (called
154152
I<fields> or I<instance storage> in other languages). Just as a C<my>
@@ -231,6 +229,29 @@ evaluated at that time, and can even reference earlier attributes:
231229
has Task @!dependencies;
232230
has $.ready = not @!dependencies;
233231
232+
X<|class variables>
233+
A class declaration can also include I<class variables>, which are variables that are shared by all instances, and can be used for things like counting the number of instantiations or any other shared state. Class variables use the same syntax as the rest of the attributes, but are declared as C<my> or C<our>, depending on the scope; the second type of variables will be used across the class hierarchy.
234+
235+
=begin code
236+
class Str-with-ID is Str {
237+
my $.counter = 0;
238+
has Str $.string;
239+
has Int $.ID;
240+
241+
method new( Str $string ) {
242+
self.bless( $:string, ID => $.counter++ )
243+
}
244+
}
245+
246+
say Str-with-ID.new('First').ID; # OUTPUT: «0»
247+
say Str-with-ID.new('Second').ID; # OUTPUT: «1»
248+
=end code
249+
250+
In this case, using C<new> might be the easiest way to initialize the C<$.ID>
251+
field and increment the value of the counter at the same time. C<new>, through
252+
C<bless>, will invoke the default C<BUILD>, assigninng the values to their
253+
properties correctly.
254+
234255
=head1 Static fields?
235256
236257
Perl 6 has no B<static> keyword. Nevertheless, any class may declare anything

0 commit comments

Comments
 (0)