【问题标题】:Call superclass apply method in scala在scala中调用超类应用方法
【发布时间】:2017-10-24 08:58:20
【问题描述】:
trait A {
    def a
    def b
    def c
}

object A {
    def apply = {
        new A {
            def a = 1
            def b = 2
            def c = 3
        }
    }
}

看到我在这里有一个特征 A,并且伴随对象的 apply 方法实现了它。

trait B extends A {
    def d
}

object B {
    def apply = {
        new B {
            def d = 4
        }
    }
}

Trait B 当然不会编译,因为我还必须实现 A 的 a/b/c 方法,但是有没有一种方法可以调用 A 的 apply 方法,然后只实现 B 的 d 方法?

我认为在 B.apply 中覆盖 a/b/c 并调用 super.a/b/c 是一种方法,但如果它有多个层 A->B->C->D,我不这样做'不想覆盖叶子节点中所有超类的方法。

任何想法都会有所帮助,谢谢!

【问题讨论】:

    标签: scala inheritance apply multiple-inheritance companion-object


    【解决方案1】:

    如果A可以改的话,我觉得最合理的解决办法是给A.apply()返回的匿名类起个名字:

    object A {
        class AImpl extends A {
            def a = 1
            def b = 2
            def c = 3
        }
        def apply = new AImpl
    }
    
    object B {
        def apply = {
            new AImpl with B {
                def d = 4
            }
        }
    }
    

    我认为在 B.apply 中覆盖 a/b/c 并调用 super.a/b/c 是一种方法

    不,这行不通。如果是这样,则无需覆盖它们。

    【讨论】:

    • 非常感谢,它有效!我最终在对象 B 中也有 BImpl,它适用于多层继承。
    猜你喜欢
    • 2012-12-30
    • 2011-10-14
    • 1970-01-01
    • 2021-11-10
    • 2011-03-28
    • 2020-05-27
    • 1970-01-01
    • 2011-03-02
    • 1970-01-01
    相关资源
    最近更新 更多