Skip to content

Commit 5cd0d2a

Browse files
committed
[traps] BUILD and attribute initialization
1 parent 2ed8f99 commit 5cd0d2a

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

lib/Language/traps.pod

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,55 @@ So the correct way to write method double is
5151
5252
which operates on the attributes directly.
5353
54+
=head2 BUILD prevents automatic attribute initialization from constructor arguments
55+
56+
When you define your own C<BUILD> submethod, you must take care of
57+
initializing all attributes yourself. For example
58+
59+
use v6;
60+
class A {
61+
has $.x;
62+
has $.y;
63+
submethod BUILD {
64+
$!y = 18;
65+
}
66+
}
67+
68+
say A.new(x => 42).x; # Any
69+
70+
leaves C<$!x> uninitialized, because the custom C<BUILD> doesn't initialize
71+
it. And the custom BUILD
72+
73+
One possible remedy is to explicitly initialize the attribute in C<BUILD>:
74+
75+
submethod BUILD(:$x) {
76+
$!y = 18;
77+
$!x := $x;
78+
}
79+
80+
which can be shortened to
81+
82+
submethod BUILD(:$!x) {
83+
$!y = 18;
84+
}
85+
86+
Another, more general approach is to leave C<BUILD> alone, and hook into the
87+
C<BUILDALL> mechanism instead:
88+
89+
use v6;
90+
class A {
91+
has $.x;
92+
has $.y;
93+
method BUILDALL(|c) {
94+
nextsame;
95+
$!y = 18;
96+
}
97+
}
98+
99+
say A.new(x => 42).x; # 42
100+
101+
102+
54103
=head1 Regexes
55104
56105
=head2 Whitespace in Regexes does not match literally

0 commit comments

Comments
 (0)