Front page | perl.perl6.users |
Postings from December 2018
Tricks: class cloning
From:
Vadim Belman
Date:
December 22, 2018 15:45
Subject:
Tricks: class cloning
Message ID:
F92A3F2A-B17C-4A65-8628-C8367A7F7D4E@lflat.org
Hi!
Another question to improve understanding of Perl6 internals.
Let's say, I've got an idea of allowing a user to define a 'template' class. I.e. it wouldn't be used directly, but I could be used as a base for creating a new one (or a couple of new ones – it would depend). Basically, what is needed to perform this operation is to create the new class, then copy methods/attributes from the template and then set those properties I would need (like parent class, for example). The following code even do some of the job:
class Foo {
...
method foo { ... }
}
my \type = Metamodel::ClassHOW.new_type( name => 'Foo-clone' );
for Foo.^methods(:local) -> $m {
next if $m.?is-hidden-from-backtrace;
type.^add_method( $m.name, $m.clone );
}
type.^compose;
my $inst = type.new;
$inst.foo;
Except that that .foo cannot be called on Foo-clone because it has an implicit constraint Foo:D for 'self'. I tried re-compose the method signature and pass it to method's clone:
$m.clone( :$signature );
but ended up with 'unexpected named parameter' error. So far, this is where I stuck and would like to know if there is a workaround for this?
Basically, what I'm trying to achieve is could also be done by using a role as a template which could then be applied to the custom class. But roles has a few restrictions which would make them less flexible.
Best regards,
Vadim Belman
-
Tricks: class cloning
by Vadim Belman