12

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?

Ryan Stull
  • 958
  • 1
  • 9
  • 15
  • 1
    http://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 https://code.google.com/p/groovypptest/wiki/Traits – Vorg van Geir Sep 21 '14 at 11:33
  • You should really read the [docs](http://docs.groovy-lang.org/next/html/documentation/core-traits.html) 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 '19 at 00:15

1 Answers1

6

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.

fxfour
  • 76
  • 3
  • 4
    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 '19 at 06:55
  • 1
    A trait allows you to define regular fields, not just static fields as java's interface limits you to – smac89 Jun 22 '19 at 22:47
  • If you are confused about traits, [read the docs](http://docs.groovy-lang.org/next/html/documentation/core-traits.html). They are very informative – smac89 Jun 23 '19 at 00:16
  • 1
    @smac89, thanks, that was really helpful! – olyv Jul 22 '19 at 07:52