【问题标题】:Perl6 Class inheritance when classes are in different "namespaces/packages"当类位于不同的“命名空间/包”中时的 Perl6 类继承
【发布时间】:2018-10-31 22:44:28
【问题描述】:

假设有 A::Very::Shallow::ClassA 和 A::Very::Deep::ClassB

文件:./A/Very/Shallow/ClassA.pm6

class A::Very::Shallow::ClassA{
   has Str $.label is rw;
   has Str $.icon is rw;
   has @.items is rw;
}

我想在 ClassB 中继承 ClassA 所以我写:

文件:./A/Very/Deep/ClassB.pm6

class A::Very::Deep::ClassB is A::Very::Shallow::ClassA{
...
}

但是错误是:

Cannot resolve caller trait_mod:<is>(A::Very::Deep::ClassB, A::Very::Shallow::ClassA, Hash); none of these signatures match:
    (Mu:U $child, Mu:U $parent)
    (Mu:U $child, :$DEPRECATED!)
    (Mu:U $type, :$rw!)
    (Mu:U $type, :$nativesize!)
    (Mu:U $type, :$ctype!)
    (Mu:U $type, :$unsigned!)
    (Mu:U $type, :$hidden!)
    (Mu:U $type, Mu :$array_type!)
    (Mu:U $type, *%fail)
    (Attribute:D $attr, |c is raw)
    (Attribute:D $attr, :$rw!)
    (Attribute:D $attr, :$readonly!)
    (Attribute $attr, :$required!)
    (Attribute $attr, Mu :$default!)
    (Attribute:D $attr, :$box_target!)
...

我找到了大量关于继承的文档和示例,但似乎没有一个涵盖我认为简单的基本问题。我知道答案可能很明显,但我现在想念它。

当类与在同一个包中时会发生什么

A::Money::Card is A::Money::Item

我现在有点困惑,所以任何指针都会很棒。提前谢谢你。

【问题讨论】:

    标签: class inheritance raku


    【解决方案1】:

    在课程的开头{ 之前缺少空格。改成这样:

    class A::Very::Deep::ClassB is A::Very::Shallow::ClassA {
    }
    

    应该可以正常工作(前提是A::Very::Shallow::ClassA 有一个use 声明)。

    当然,了解为什么这个空间很重要也很有趣。

    is 语法只是更通用的特征语法的一种情况。使用特征,它可以与特征名称一起传递额外的参数。最常见的形式可能是使用导出标签时:is export(:util)。但是,也可以传递数组 (is foo[1, 2, 3])、引号 (is bar&lt;x y z&gt;) 或哈希 (is baz{ a =&gt; 1, b =&gt; 2 })。 (顺便说一句:事实上,这与在冒号对语法中工作的东西完全相同,因此命名参数:foo([1, 2, 3]) 可以改为:foo[1, 2, 3]);

    因此,is Something{} 将您希望的类主体作为空的 Hash 参数传递给特征。一个 trait 只是一个多调度 sub,并且没有匹配的候选者,这解释了错误中提到 Hash 和调度失败。

    【讨论】:

    • 该死!!!我不敢相信它像空间一样简单,但是解释很棒。非常感谢。
    • @DanielMaldonado,在 Perl 6 中,空格通常很重要,因为它们必须存在或不必存在。
    猜你喜欢
    • 2017-12-21
    • 1970-01-01
    • 2015-07-18
    • 2017-12-10
    • 2021-08-12
    • 2020-05-02
    • 2011-01-15
    • 2011-05-29
    • 1970-01-01
    相关资源
    最近更新 更多