I'm trying to write a Factory pattern in Perl6, and I need to pass the same arguments to the constructor of each class. All the examples of Perl6 Factories out there right now seem to have neglected trying to pass arguments.

In Perl5, I would probably set a variable to hold the classname, and then pass the args after we figure out where we want to go.

my $class = $type == 0 ? 'ClassA' : $type == 1 ? 'ClassB' : 'ClassC'; my $obj = $class->new( foo => 1, bar => 2 );

Alternatively, you can wrap up the arguments and rely on list flattening to take care of it:

my %args = ( foo => 1, bar => 2 ); my $class = $type == 0 ? ClassA->new( %args ) : $type == 1 ? ClassB->new( %args ) : 'ClassC';

My first attempt in Perl6 followed the first method above:

my $class; given $type { when 0 { $class = ClassA } when 1 { $class = ClassB } default { $class = ClassC } } my $obj = $class.new( foo => 1, bar => 1 );

But this resulted in an object from Any, not the class I wanted.

I also took a stab at the second method, attempting to use the | list flattening operator:

my @args = ( foo => 1, bar => 1 ); my $obj; given $type { when 0 { $obj = ClassA.new( |@args ) } when 1 { $obj = ClassB.new( |@args ) } default { $obj = ClassC.new( |@args ) } }

Along with a few variations, most of which failed with Default constructor for 'ClassA' only takes named arguments.

Help for either option would be enlightening.


"There is no shame in being self-taught, only in not trying to learn in the first place." -- Atrus, Myst: The Book of D'ni.


In reply to Factory Pattern in Perl6 by hardburn

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.