98. Trait static members

As demonstrated in the example below, traits can have static properties, fields and methods:

Traits and static members
trait Running {
    static final MAX_DISTANCE = 10_000

    static public final MAX_COMPETITORS = 12

    static describeRules() {
        println 'Here are the rules of running....'
    }
}

class SportingEvent implements Running {

}

assert SportingEvent.MAX_DISTANCE == 10_000

assert SportingEvent.Running__MAX_COMPETITORS == 12

SportingEvent.describeRules()
  • Accessing a static property: SportingEvent.MAX_DISTANCE
  • Accessing a static field: SportingEvent.Running__MAX_COMPETITORS
  • Accessing a static method: SportingEvent.describeRules()

Static member support doesn’t appear to be “fully baked” at this time so it’s a good idea to keep an eye on the Groovy documentation.