No, it's not possible to redeclare an attribute - but you can initialize it using the BUILD
submethod of the class:
role A {
has $.a;
}
class B does A {
submethod BUILD(:$!a = 'default') {}
}
Note that if you just set the value within the body of BUILD
instead of its signature via
class B does A {
submethod BUILD { $!a = 'default' }
}
the user would not be able to overwrite the default by providing a named initializer via B.new(a => 42)
.
Another, more elegant approach that is especially useful if setting the default is something you expect to do a lot (ie the default value can be regarded as part of the role's interface) is making it a parameter:
role A[$d] {
has $.a = $d;
}
class B does A['default'] {}