Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

raku - pointer to constructor to a class in perl6

I am trying to write some classes with Perl 6 just for testing out Perl 6 classes and methods.

Here is the code:

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

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

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

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

print "now trying more complex stuff
";

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

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

Essentially I want to be able to use either the human1 constructor or human2 constructor to be able to build $c object dynamically. But I'm getting 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 $c using the function pointers to choose which constructor I use?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To get a “reference” to .new you have to use the meta object protocol.
Either .^lookup, or .^find_method.

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

That is still not quite what you are looking for, as methods require either a class object or an instance, as their first argument.

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

So you would probably want to curry the class as the first argument to the method.

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

my $c = $hum1-create();

Note that .assuming in this case basically does the same thing as

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

So you could just write:

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

Or if you are never going to give it an argument

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

Also you can store it in a & sigiled variable, so you can use it as if it were a normal subroutine.

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

my $c = hum1-create;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...