Pointer to class constructor in perl6

I am trying to write some classes with Perl 6 only to test Perl 6 classes and methods.

Here is the code:

class human1 {
    method fn1() {
        print "#from human1.fn1\n";
    }
}

class human2 {
    method fn1() {
          print "#from human2.fn1\n";
    }
}

my $a = human1.new();
my $b = human2.new();

$a.fn1();
$b.fn1();

print "now trying more complex stuff\n";

my $hum1_const = &human1.new;
my $hum2_const = &human2.new;

my $c = $hum2_const();
$c.fn1();

Essentially, I want to be able to use a constructor human1or constructor human2to dynamically create an object $c. But I get the following error:

Error while compiling /usr/bhaskars/code/perl/./a.pl6
Illegally post-declared types:
    human1 used at line 23
    human2 used at line 24

How do I create $cusing function pointers to choose which constructor I use?

+4
source share
2 answers

I think this is a case of LTA error. I understand what you want to achieve is a lambda that will create a new object for you human1or human2. The way you do this is wrong, and the error it causes is confused.

my $hum1_const = -> { human1.new };
my $hum2_const = -> { human2.new };

. , . human1 human2 , , new :

my $the_human = $condition ?? human1 !! human2;
my $c = $the_human.new;
$c.fn1;

?

+3

.new, .
.^lookup, .^find_method.

my $hum1-create = human1.^find_method('new');

, , , .

my $c = $hum1-create( human1 );

, , , .

my $hum1-create = human1.^find_method('new').assuming(human1);

my $c = $hum1-create();

, .assuming ,

-> |capture { human1.^find_method('new').( human1, |capture ) }

, :

my $hum1-create = -> |capture { human1.new( |capture ) }

,

my $hum1-create = -> { human1.new }

& sigiled, , .

my &hum1-create = human1.^find_method('new').assuming(human1);

my $c = hum1-create;
+3

Source: https://habr.com/ru/post/1691418/


All Articles