【问题标题】:How do you fill a Callable attribute via clone?如何通过克隆填充 Callable 属性?
【发布时间】:2019-02-12 00:46:57
【问题描述】:
class Foo {
    has &.bar;
    has @.quux is required;
    method clone { nextwith :quux(@!quux.clone) };
    # as per <https://docs.perl6.org/type/Mu#method_clone>
};
my $f = Foo.new(quux => []);
my $f-clone = $f.clone(bar => sub { die });
# Foo.new(bar => Callable, quux => [])

但应该是

Foo.new(bar => sub { #`(Sub|94789546929784) ... }, quux => [])

:bar(&amp;!bar.clone) 添加到nextwith 调用没有帮助。

【问题讨论】:

  • 您可以尝试将参数转发到clonenextsame,例如:method clone(*%twiddles) { nextwith(:quux(@.quux.clone), |%twiddles)
  • 确实有效,请转换为答案,以便我接受
  • @HåkonHægland 已转换。 (实际上我独立地看到了同样的事情,但我喜欢有一个很好的答案,所以我需要一段时间。在这种情况下,我找不到合适的文档引用包括%_。我花了一段时间才放弃.)
  • @raiph 优秀:)

标签: raku


【解决方案1】:

nextwith“使用用户提供的参数调用下一个匹配的候选者”。您只是在 nextwith 调用中传递了 :quux 参数。

除非您添加显式的 slurpy 哈希参数(例如 *%foo),否则所有方法的签名中都会隐含 *%_

say .signature given method ($a, $b) {} # (Mu: $a, $b, *%_)

所以默认情况下,所有命名参数都被吞入%_。一个常见的习惯是传递这些:

method clone { nextwith :quux(@!quux.clone), |%_ }

以上内容会将提供给$f.clone 调用的参数传递给nextwith'd clone 调用。

:bar(&amp;!bar.clone) 添加到nextwith 调用没有帮助。

这将是而不是$f.clone 调用中传递的:bar 参数。原始对象中的&amp;!bar 包含Callable 类型的对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-04
    • 1970-01-01
    • 2015-04-02
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    • 2016-05-07
    • 2014-02-18
    相关资源
    最近更新 更多