Course of Raku / Objects, I/O, and exceptions / Classes and objects / Attributes

Default values

An attribute can be given a default value, which is used when an object is created without a value for it. Write the default after the attribute, with =:

class Dog {
    has Str $.name;
    has Rat $.weight = 4.0;
}

Notice that similar to variables, it is possible to force the type of the attributes.

If you do not pass weight to new, the attribute takes the default:

my $rex = Dog.new(name => 'Rex');
say $rex.weight; # 4

You can still override the default by passing a value:

my $lighty = Dog.new(name => 'Lighty', weight => 3.2);
say $lighty.weight; # 3.2

Without a default, and without a value passed to new, an attribute is simply undefined, exactly like a fresh scalar variable.

Practice

Complete the quiz that covers the contents of this topic.

Course navigation

Read-write attributes   |   Quiz — Attributes


💪 Or jump directly to the exercises in this section.