Can I move stackable trait logic to parent?

I'm not sure is it possible or I'm asking the wrong question here. Let's say if I have something like

trait Parent {
    def foo : String = " Parent "
}

trait Child1 extends Parent {
    override def foo : String = super.foo + " Child 1 "
}

trait Child2 extends Parent {
    override def foo : String = super.foo + " Child 2 "
}

and use it like

class ChildGroup extends Child1 with Child2
(new ChildGroup).foo

the result as expected be " Parent Child 1 Child 2 "

but I found it hard to maintain, especially when someone else use my trait and didn't use it the way I meant

trait Child3 extends Parent //<-- not override foo, and no error

trait Child4 extends Parent {
    override def foo : String = " Child 4 " //<-- forget super.foo +
}

and use like

class ChildGroup extends Child1 with Child2 with Child3 with Child4
(new ChildGroup).foo

the result will be just " Child 4 " and I don't want that to happen I just want it to always be stack

So It would be nice to move all the logic of stack trait to Parent

Is it possible to do that? or there are other option that will force other people to always do super.foo + x

Answers


This is Object Oriented question.

you can define parent as :

trait Parent{
    public final def f():String= {
              "Parent" +g();
    }
    protected abstract def g():String
}

trait Child extends Parent{
    def g()= "Child"
}

enforcing parent functionality to run firstly before single child. if you have multiple children and you want to apply all of those functionality when calling to one function, I think it's abusive to use mixin technique like that, this is not the purpose for this technique (adding functionality).

If you would like to add functionality to a function please take a look at the Decorator design pattern.

regards trait Child3 extends Parent //<-- not override foo, and no error it is not possible using reular coding. you can define macro, but I would not suggest it because it's experimental which means it can be removed from the scala sdk.


Need Your Help

Help, my CentOS servers keep going down , No route to host after a random uptime

linux centos uptime

I have a couple of Centos linux servers, that have a very simple task, they run nginx + fastcgi for php , and some NFS mounts between them, readonly

Loading a file with more than one line of JSON into Python's Pandas

python json python-2.7 pandas

I am trying to read in a json file into pandas data frame. Here is the first line line of the json file: