@@ -37,9 +37,32 @@ In the two classes, the default constructor is being used. This
37
37
constructor will use named parameters in its invocation: C « Point.new(x =>
38
38
0, y => 0) » .
39
39
40
- You can also provide your own construction and C < BUILD > implementation. The
41
- following, more elaborate example shows how a dependency handler might look in
42
- Perl 6. It showcases custom constructors, private and public attributes,
40
+ You can also provide your own construction and C < BUILD > implementation. You need to do it in the case there are private attributes, like below:
41
+
42
+ = begin code
43
+ class Hero { #taken from https://medium.freecodecamp.org/a-short-overview-of-object-oriented-software-design-c7aa0a622c83
44
+ has @!inventory;
45
+ has Str $.name;
46
+ submethod BUILD( :$name, :@inventory ) {
47
+ $!name = $name;
48
+ @!inventory = @inventory
49
+ }
50
+
51
+ method act {
52
+ return @!inventory.pick;
53
+ }
54
+ }
55
+ my $hero = Hero.new(:name('Þor'),
56
+ :inventory(['Mjölnir','Chariot','Bilskirnir']));
57
+ say $hero.act;
58
+ = end code
59
+
60
+ In this case, we I < encapsulate > the private attribute C < @!inventory > ; but
61
+ private instance variables cannot be set by the default constructor, which is
62
+ why we add a C < BUILD > submethod that takes care of that.
63
+
64
+ The following, more elaborate example, shows how a dependency handler might look
65
+ in Perl 6. It showcases custom constructors, private and public attributes,
43
66
L < Submethod|/type/Submethod > s, methods, and various aspects of signatures. It's
44
67
not a lot of code, and yet the result is interesting and useful.
45
68
@@ -84,12 +107,12 @@ my $eat =
84
107
$eat.perform();
85
108
= end code
86
109
87
- In this case, C < BUILD > is needed since we have overridden the default
88
- new. C < bless > is eventually invoking it with
89
- the two named arguments that correspond to the two properties without a
90
- default value. With its signature , C < BUILD > converts the two positionals
91
- to the two attributes, C < &!callback > and C < @!dependencies > , and returns
92
- the object (or turns it in to the next phase, C < TWEAK > , if available).
110
+ In this case, C < BUILD > is needed since we have overridden the default new.
111
+ C < bless > is eventually invoking it with the two named arguments that correspond
112
+ to the two properties without a default value. With its signature, C < BUILD >
113
+ converts the two positionals to the two attributes , C < &!callback > and
114
+ C < @!dependencies > , and returns the object (or turns it in to the next phase,
115
+ C < TWEAK > , if available).
93
116
94
117
Declaring C < new > as a C < method > and not a C < multi method > prevents us
95
118
from using the default constructor; this implicit constructor uses the
0 commit comments