Reputation: 79
I am working on an existing java codebase but have convinced the team to use cross compilation so new development can be done in groovy, while still using the old codebase. Best of both worlds, low risk, lots of benefits, etc.
I have a problem i am trying to solve that is perfectly handled by Groovy's trait feature, but it has to work with the existing java classes or new ones for the dev's that still want to write in java.
doing class duck implements FlyingAbility {
in java throws an error about implementation, and IntelliJ's automatix fix is to implement all of the methods in the trait in the java class, as if it was just an interface.
Is there a way to have traits use traits in java classes similarly to how they work in groovy classes?
Upvotes: 2
Views: 1656
Reputation: 3246
If you need to use just one trait you can create a proxy class in Groovy i.e.
GroovyTrait.groovy
trait GroovyTrait {
}
GroovyClass.groovy
class GroovyClass implements GroovyTrait {
}
JavaClass.java
class JavaClass extends GroovyClass {
}
Upvotes: 1
Reputation: 77187
You can't use traits in Java classes. Groovy traits are implemented as a compile-time transformation of the class they're applied to, and Java classes don't pass through the Groovy compiler.
That said, it's usually very simple to convert Java code to Groovy, and adding @CompileStatic
to the class typically generates code that performs about like the equivalent Java, although (for now) with a bit larger .class
file.
Upvotes: 5