My first guess is that your class declarations (which you didn't list) declare attributes without a public accessor rather than with one (ie you're using has $!foo instead of has $.foo). The official docs touch on this here. I'll discuss this more if it turns out to be the issue and you reply here requesting more info.
You didn't include enough code for me to confidently figure out what's going wrong. The first method works for me:
use v6.c; say $*PERL.compiler.version; class ClassA {}; class ClassB {} class ClassC { has $.foo; has $!bar; }; my $class; given 2 { when 0 { $class = ClassA } when 1 { $class = ClassB } default { $class = ClassC } } say my $obj = $class.new( foo => 1, bar => 1 );
This displays:
v2016.04 ClassC.new(foo => 1)
The second method should work too. That's incorrect. An update to correct my mistake follows. To insert named arguments you need a container like my %args, eg:
class ClassC { has $.foo } my %args = :foo; ClassC.new(|%args)
A Positional container as declared by my @args inserts positional arguments into an argument list. The "Default constructor ... only takes named arguments" comes up if you call a .new method that, through inheritance, calls the positional argument version of the new method from the root class Mu, eg:
class C {} C.new(1)
If you want a constructor that takes positional arguments you have to write one yourself like this one declared in the Duration class shipped with Perl 6:
class Duration ... { has Rat $.tai = 0; ... method new($tai) { self.bless: tai => $tai.Rat } ... }
So the Duration class's .new can accept a positional argument, eg:
say Duration.new(22); # Duration.new(tai => 22.0)
Hopefully that's of some use.
»ö« . o O ( "the celebrity tell-all of the Perl-6 cult?" )
In reply to Re: Factory Pattern in Perl6
by raiph
in thread Factory Pattern in Perl6
by hardburn
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |