Course of Raku / Objects, I/O, and exceptions / Classes and objects / Attributes / Exercises / A counter
Solution: A counter
Here is a possible solution to the task.
Code
class Counter {
has $.count is rw = 0;
}
my $c = Counter.new;
say $c.count;
$c.count++ for ^5;
say $c.count;🦋 You can find the source code in the file counter.raku.
Output
0
5Comments
The attribute is declared
is rwso that its accessor returns a writable container, and= 0gives it a starting value. The firstsayconfirms a fresh counter really does begin at that default,0.Because the accessor is writable, incrementing it with
++works as expected.