Skip to content

Commit d99e1cf

Browse files
committed
Improve classtut example again
* Bring back private attributes (BUILD submethod needed to bind them properly). * Add some doc explaining the BUILD usage in the example.
1 parent e115f9f commit d99e1cf

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

lib/Language/classtut.pod

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,22 +13,24 @@ result is interesting and, at times, useful.
1313
1414
=begin code
1515
class Task {
16-
has &.callback;
17-
has Task @.dependencies;
16+
has &!callback;
17+
has Task @!dependencies;
1818
has Bool $.done;
1919
2020
method new(&callback, *@dependencies) {
2121
return self.bless(:&callback, :@dependencies);
2222
}
2323
24+
submethod BUILD(:&!callback, :@!dependencies) { }
25+
2426
method add-dependency(Task $dependency) {
2527
push @!dependencies, $dependency;
2628
}
2729
2830
method perform() {
2931
unless $!done {
30-
.perform() for @.dependencies;
31-
&.callback.();
32+
.perform() for @!dependencies;
33+
&!callback();
3234
$!done = True;
3335
}
3436
}
@@ -253,6 +255,21 @@ into the C<@dependencies> slurpy array and passes them as named parameters to
253255
C<bless> (note that C<:&callback> uses the name of the variable--minus the
254256
sigil--as the name of the parameter).
255257
258+
X<|BUILD>
259+
260+
Private attributes really are private. This means that C<bless> is not allowed
261+
to bind things to C<&!callback> and C<@!dependencies> directly. To do this, we
262+
override the C<BUILD> submethod, which is called on the brand new object by
263+
C<bless>:
264+
265+
submethod BUILD(:&!callback, :@!dependencies) { }
266+
267+
Since C<BUILD> runs in the context of the newly created C<Task> object, it is
268+
allowed to manipulate those private attributes. The trick here is that the
269+
private attributes (C<&!callback> and C<&!dependencies>) are being used as the
270+
bind targets for C<BUILD>'s parameters. Zero-boilerplate initialization! See
271+
L<objects|/language/objects#Object Construction> for more information.
272+
256273
=head1 Consuming our class
257274
258275
After creating a class, you can create instances of the class. Declaring a

0 commit comments

Comments
 (0)