Suppose I have a class with a default attribute

    class Foo { has Int $.a = 1; }

Now I want to write a custom constructor for it, with either `Foo.new()` or
`Foo.new(3)` doing the obvious thing. Here's one way to do it:

    multi method new(Int $a = 1) { self.new(:$a); }

but this duplicates the default. Here's another:

    multi method new() { self.new; }
    multi method new(Int $a) { self.new(:$a); }

but this becomes horrible outside of the trivial cases.

I'm wondering if there's an idiomatic way to handle this without
duplicating the default. I think what I really want is something that says
"if $a is defined, then pass the named argument :$a; otherwise, pass
nothing". Something along the lines of

    self.new(:a($a // Slip))

would be pretty good, except that Slip doesn't work like that, at least not
currently.

Another way to solve the same problem might be something like

    multi method new(Int $a = Foo.^defaults<$a>) { self.new(:$a); }

if there was an easy way to access a class's variable defaults. (Is there
one that I don't know of?)

This isn't necessarily a big deal - right now I'm happy to just duplicate
my defaults - but it seems like something that's going to be a minor
annoyance in a lot of places.

Reply via email to