In Attribute§
See primary documentation in context for trait is required.
multi trait_mod:<is> (Attribute $attr, :$required!)
The trait is required will mark the attribute as to be filled with a value when the object is instantiated. Failing to do so will result in a runtime error.
class C { has $.a is required } my $c = C.new; CATCH{ default { say .^name, ': ', .Str } } # OUTPUT: «X::Attribute::Required: The attribute '$!a' is required, but you did not provide a value for it.»
This trait also allows attributes to be typed with types that have a :D smiley without giving them a default value:
class Power { has Numeric:D $.base is required; has Numeric:D $.exponent is required; multi method Numeric(::?CLASS:D: --> Numeric:D) { $!base ** $!exponent } }
Available as of 6.d language version (early implementation exists in Rakudo compiler 2018.08+): You can specify a reason why the attribute is required:
class D { has $.a is required("it is a good idea"); } my $d = D.new; CATCH{ default { say .^name, ': ', .Str } } # OUTPUT: «X::Attribute::Required: The attribute '$!a' is required because it is a good idea,but you did not provide a value for it.»
is required doesn't just affect the default constructor, it checks for the attribute at a lower level, so it will work for custom constructors written using bless.