Constructor with 1 argument in Perl 6

I want to override new so that my class can only be created by passing one argument to the constructor, no more and no less.

 class MyClass { has $.var1; method new($var1) { return MyClass.new(var1 => $var1); } } my $my_class1 = MyClass.new(33); say $my_class1.var1; 

Error:

 Too few positionals passed; expected 2 arguments but got 1 in method new at test1.pl6:28 in method new at test1.pl6:28 in block <unit> at test1.pl6:33 

What about him?

+6
source share
1 answer

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!

+10
source

All Articles