Custom constructors should call bless , i.e.
class MyClass { has $.var1; method new($var1) { return self.bless(var1 => $var1); } }
There are several things that can be improved, for example
- you can add an explicit invocant parameter and use
:U to make .new() fail when calling instance objects - explicit
return superfluous - the last expression inside the method will be returned anyway, and currently it is actually hurting performance - there is syntactic sugar for passing a named argument stored in a variable with the same name
Combining all this, we get
class MyClass { has $.var1; method new(MyClass:U: $var1) { self.bless(:$var1); } }
As for your error, follow these steps:
Your new method is declared to accept a positional argument (giving a total of 2 expected arguments due to an implicit invocant), but a call to MyClass.new(var1 => $var1) only passed the named one. Note that this method is the only .new() present in your class, so if the call really worked, you would end up with infinite recursion!
source share