Limit the types that Trait can implement

Is it possible to limit the types that can implement a trait? Say for example, I have a type

interface Something { void foo() } 

and sign

 trait SomethingAbility { void bar() { println "bar" } } 

Is there a way that I can only allow attribute implementation by classes that are of type Something , for example.

 // OK class SomethingImpl implements Something, SomethingAbility { void foo() { println "foo" } } // error: this class should not be allowed to implement the trait // because it not a Something class NotSomething implements SomethingAbility { void foo() { println "foo" } } 

One option is to add an abstract method to the attribute

 trait SomethingAbility { void bar() { println "bar" } abstract void foo() } 

This means that this attribute cannot be implemented by the class if this class does not provide the foo() method, but this is not the same as a class of type Something

+6
source share
1 answer

I think you're looking for @Selftype, see http://docs.groovy-lang.org/docs/latest/html/gapi/groovy/transform/SelfType.html Basically, this tells which class this should use this sign. So,

 @SelfType(Something) trait SomethingAbility { void bar() { println "bar" } } 

you declare that any class using this attribute will also have to implement the Something interface. This ensures, for example, that if you statically compile a tag and you invoke a method from the Something interface, this compilation will not fail. Of course, this is not required for standard Groovy, due to duck input.

+9
source

Source: https://habr.com/ru/post/984311/


All Articles