Search code examples
scalainheritanceapplymultiple-inheritancecompanion-object

Call superclass apply method in scala


trait A {
    def a
    def b
    def c
}

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

See i have a trait A here and the companion object's apply method implements it.

trait B extends A {
    def d
}

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

Trait B of course won't compile since I have to also implement A's a/b/c methods, but is there a way I can call A's apply method and then just implement B's d method?

I think to override a/b/c in B.apply and just call super.a/b/c is one way, but what if it has multiple layers A->B->C->D, I don't want to override all superclass's method in the leaf node.

Any thoughts would help, thanks!


Solution

  • If you can change A, I think the most reasonable solution is to give a name to the anonymous class returned from 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
            }
        }
    }
    

    I think to override a/b/c in B.apply and just call super.a/b/c is one way

    No, that won't work. If it did, there would be no need to override them.