I'm learning groovy and I've just learned about the new feature added in 2.3, which is the addition of Traits. Now to me it seems like Traits allow you to do basically everything a super-class and an Interface can do.

Does the addition of Traits to Groovy make Inheritance and Interfaces obsolete?

And if not, then what is the best time to use each of these mechanisms?

  • 1
    stackoverflow.com/q/23121890 – Robert Harvey Aug 13 '14 at 19:01
  • "groovy and I've just learned about the new feature added in 2.3, which is the addition of Traits" - Traits were first added to pre-2.0 Groovy via an AST addon called the Groovy++ booster, see code.google.com/p/groovypptest/wiki/Traits – Vorg van Geir Sep 21 '14 at 11:33
  • You should really read the docs about traits. No answer given here will be complete without mentioning everything those docs talk about; You should especially pay attention to sections 13 - end – smac89 Jun 23 at 0:15

Traits combine the best of both worlds - the inheritance of (abstract) classes and the implementation of interfaces. A trait can contain default implementations of methods and yet a type can implement multiple traits at once. This allows some kind of multiple inheritance, but in a good way, avoiding the deadly diamond of death.

If you don't know how to start, then use traits. You gain flexibility and can switch to interfaces or class inheritance later on if required.

  • 3
    In interfaces you can define default method, so what is the logical difference ? – Gilad Baruchian Jul 20 '17 at 15:25
  • i am also confused with the difference between traits and interface default methods. I can only assume traits in groovy were introduced earlier than default methods in java – olyv May 17 at 6:55
  • A trait allows you to define regular fields, not just static fields as java's interface limits you to – smac89 Jun 22 at 22:47
  • If you are confused about traits, read the docs. They are very informative – smac89 Jun 23 at 0:16
  • 1
    @smac89, thanks, that was really helpful! – olyv Jul 22 at 7:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.