Skip to content

Commit 61d8402

Browse files
authored
Merge pull request #4727 from Raku/librasteve-moreontraits
More Information on Attribute Traits
2 parents b0b065e + a342aa9 commit 61d8402

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

doc/Language/objects.rakudoc

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,53 @@ attributes, it will only set attributes that have an accessor method.
271271
That is, even if you pass C«travelers => ["Alex", "Betty"]» to the
272272
default constructor, the attribute C<@!travelers> is not initialized.
273273

274+
=head2 Traits
275+
276+
Several traits are provided to modify the behavior of attributes.
277+
Attribute traits are introduced by the C<is> keyword after the attribute name.
278+
The following traits (and some others) are documented L<here|/type/Attribute#Traits>.
279+
280+
=begin code
281+
class Journey {
282+
# error if origin is not provided
283+
has $.origin is required;
284+
# reset to this default value if Nil is assigned
285+
has $.destination is default('Orlando') is rw;
286+
# private attribute
287+
has @!travelers;
288+
# is read/write
289+
has $.notes is rw;
290+
# is readonly
291+
has $.agent is readonly = 'Acme Travel Inc.';
292+
# private attribute can (only) be set via .new
293+
has $!status is built;
294+
}
295+
=end code
296+
297+
Here's how to construct and use this new version of Journey:
298+
299+
=begin code :preamble<class Journey {}>
300+
# Create a new instance of the class.
301+
my $vacation = Journey.new(
302+
origin => 'Sweden',
303+
status => 'Requested'
304+
);
305+
306+
# Use a setter accessor on a read/write attribute, then a getter to read it,
307+
# then assign Nil to reset the default.
308+
$vacation.destination = 'San Francisco';
309+
say $vacation.destination; # OUTPUT: «San Francisco␤»
310+
$vacation.destination = Nil;
311+
say $vacation.destination; # OUTPUT: «Orlando␤»
312+
313+
# Try to change a built private attribute later.
314+
try { $vacation.status = 'Booked'; } #ERROR
315+
=end code
316+
317+
Note that C<is readonly> is the default for attributes that are not marked C<is rw>,
318+
so in this example it has no effect. An entire class can be marked C<is rw>, in which
319+
case the C<is readonly> is useful to opt out specific attributes.
320+
274321
=head2 Methods
275322

276323
Methods are declared with the C<method> keyword inside a class body.

0 commit comments

Comments
 (0)