@@ -35,6 +35,7 @@ say $r.area(); # OUTPUT: «100»
35
35
In the two classes, the default constructor is being used. This constructor will
36
36
use named parameters in its invocation: C < Point.new(x = > 0, y => 0)>.
37
37
38
+ X < submethods >
38
39
You can also provide your own construction and C < BUILD > implementation. The
39
40
following, more elaborate example shows how a dependency handler might look in
40
41
Perl 6. It showcases custom constructors, private and public attributes,
@@ -95,6 +96,30 @@ parameters. That is one of the reasons why using C<new> is discouraged. If you
95
96
need to declare it anyway, use C < multi method new > if you do not want to disable
96
97
the default constructors.
97
98
99
+ C < TWEAK > is the last submethod to be called, and it has got the advantage of
100
+ having the object properties available without needing to use the meta object
101
+ protocol. It can be used, for instance, to assign values to instance variables
102
+ based on the values of other attributes or instance variables:
103
+
104
+ = begin code
105
+ class Str-with-ID is Str {
106
+ my $.counter = 0;
107
+ has Str $.string;
108
+ has Int $.ID;
109
+
110
+ method TWEAK() {
111
+ $!ID = $.counter++;
112
+ }
113
+ }
114
+
115
+ say Str-with-ID.new(string => 'First').ID; # OUTPUT: «0»
116
+ say Str-with-ID.new(string => 'Second').ID; # OUTPUT: «1»
117
+ = end code
118
+
119
+ In this case, we need to compute C < $.ID > from the value of a counter that is a
120
+ class variable, C < $.counter > , thus we simply assign a value to it and increment
121
+ the counter at the same time.
122
+
98
123
= head1 Starting with class
99
124
100
125
X < |class >
@@ -239,7 +264,7 @@ class Str-with-ID is Str {
239
264
has Int $.ID;
240
265
241
266
method new( Str $string ) {
242
- self.bless( $: string, ID => $.counter++ )
267
+ self.bless( :$ string, ID => $.counter++ )
243
268
}
244
269
}
245
270
@@ -250,7 +275,10 @@ say Str-with-ID.new('Second').ID; # OUTPUT: «1»
250
275
In this case, using C < new > might be the easiest way to initialize the C < $.ID >
251
276
field and increment the value of the counter at the same time. C < new > , through
252
277
C < bless > , will invoke the default C < BUILD > , assigninng the values to their
253
- properties correctly.
278
+ properties correctly. You can obtain the same effect using C < TWEAK > , which is
279
+ considered a more I < p6y > way. Please check <the section on submethods|/language/classtut#index-entry-OOP>
280
+ for an alternative example on how
281
+ to do this.
254
282
255
283
= head1 Static fields?
256
284
0 commit comments