Jerry W. Jerry W. - 3 months ago 27
Groovy Question

Can Groovy Trait Return Implementing Type Suitable for Method Chaining

Is it possible to incorporate trait methods along with methods on the implementing class using method chaining? This requires that the trait return the specific type of the implementing class, and the "this" variable is not that type by default.

Something like:

def withFilter(String filter){
this.filter = filter
return (super.getClass())this
}


According to the top answer on the post below, it looks to be pretty easy to achieve with Scala Traits, but I don't understand the syntax exactly. It looks like it uses a closure which defines it's return type, but is the same possible in Groovy?

Best practice to implement Scala trait which supports method chaining

Answer

You can use generics approach.

Here is an example

trait MyTrait<T extends MyTrait<T>> {
    def filter

    T withFilter(String filter) {
        this.filter = filter
        return (T) this
    }
}

class MyClz implements MyTrait<MyClz> {
    def clzMethod() {}
}

def clz = new MyClz()
        .withFilter("hello")
        .withFilter("another")
        .clzMethod()
Comments