File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change @@ -51,6 +51,55 @@ So the correct way to write method double is
51
51
52
52
which operates on the attributes directly.
53
53
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
+
54
103
= head1 Regexes
55
104
56
105
= head2 Whitespace in Regexes does not match literally
You can’t perform that action at this time.
0 commit comments