Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 38 ยท Classes and Traits

Groovy Traits

Learn Groovy traits: declaring and implementing them, concrete methods, state, abstract methods, multiple traits, conflict resolution, super calls, runtime traits and when to choose traits.

A Java class can extend only one parent, so sharing behavior between unrelated classes is awkward. Groovy's answer is the trait: a reusable bundle of methods and fields that a class can mix in. Think of a trait as an interface that can carry real code and state. A class can implement many traits, so you build objects from small pieces instead of long inheritance chains.

Groovy code is read-only here. The Java stand-ins use interfaces with default methods, the closest Java feature, to demonstrate the idea.

A first trait

GROOVY
trait Greeter {
    String name

    String greet() {
        "Hello, I am $name"
    }
}

class Person implements Greeter { }
class Robot implements Greeter { }

def p = new Person(name: 'Ada')
println p.greet()                 // Hello, I am Ada
println new Robot(name: 'R2').greet()   // Hello, I am R2

Person and Robot have nothing in common except Greeter, yet both receive the name property and the greet() method. A trait is declared with the keyword trait and mixed in with implements.

Compare an interface with a default method in Java, which gives behavior (but not state):

Java Java stand-in: default methods as trait-like behavior

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A Groovy trait goes further because it can declare fields and properties, as name shows.

What a trait can contain

GROOVY
trait Counter {
    private int count = 0                  // state per instance

    int increment() { ++count }
    abstract String label()                // must be provided by the class

    String report() { "${label()}: $count" }

    static String info() { 'trait static method' }
}

class Clicks implements Counter {
    String label() { 'clicks' }
}

def c = new Clicks()
c.increment(); c.increment()
println c.report()                         // clicks: 2
  • Concrete methods with bodies.
  • Abstract methods the implementing class must define.
  • Properties and fields, copied into every implementing class.
  • Static members (with some caveats about shared state).
  • Private and protected methods for internal helpers.

Multiple traits and conflict resolution

A class can implement several traits:

GROOVY
trait Walks   { String move() { 'walks' } }
trait Swims   { String move() { 'swims' } }

class Duck implements Walks, Swims { }
println new Duck().move()      // swims

When two traits define the same method, the last trait declared in implements wins. You can choose explicitly by overriding in the class and naming the trait:

GROOVY
class Frog implements Walks, Swims {
    String move() { Walks.super.move() + ' and ' + Swims.super.move() }
}
println new Frog().move()      // walks and swims

Trait.super.method() calls a particular trait's version.

Calling super in traits: the stacking pattern

Traits can wrap behavior. A trait that extends the common behavior and calls super forms a stack where each layer adds something:

GROOVY
interface Message { String text() }

class Plain implements Message {
    String text() { 'hello' }
}

trait Shout implements Message {
    String text() { super.text().toUpperCase() }
}

trait Exclaim implements Message {
    String text() { super.text() + '!' }
}

class Loud extends Plain implements Shout, Exclaim { }
println new Loud().text()      // HELLO!

Traits execute from right to left: Exclaim runs first and calls super, which reaches Shout, which calls the class's text(). Result: hello becomes HELLO and then HELLO!. Swap the order and the output changes only in the sequence of wrapping, which makes traits a clean way to compose cross-cutting behavior like logging, validation or caching.

The Java stand-in uses decorators to reproduce the stack.

Java Java stand-in: stacking behavior with wrappers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Traits that require something

A trait often depends on what the class provides. Declare it with an abstract method, or with @SelfType to demand a type:

GROOVY
import groovy.transform.SelfType

interface HasId { String getId() }

@SelfType(HasId)
trait Auditable {
    String audit() { "audited ${id}" }
}

class Order implements HasId, Auditable {
    String id = 'ORD-1'
}
println new Order().audit()      // audited ORD-1

@SelfType makes the compiler refuse to mix Auditable into a class that does not implement HasId.

Runtime traits with as and withTraits

You can add a trait to a single object at run time, without changing its class:

GROOVY
trait Flies { String fly() { "${name} flies" } }

class Bird { String name }

def b = new Bird(name: 'Tweety')
def flyer = b.withTraits(Flies)
println flyer.fly()               // Tweety flies

withTraits returns a new proxy object implementing both the original class and the trait. The expression b as Flies does a similar coercion for one trait. It is an excellent way to adapt objects you do not own.

Traits versus other tools

Tool State Multiple Best for
Class inheritance Yes No (one parent) True "is-a" hierarchies
Abstract class Yes No Shared base with template methods
Interface No (constants only) Yes Contracts
Trait Yes Yes Reusable behavior mixed into unrelated classes
@Delegate Via an inner object Yes Forwarding calls

Prefer a trait when several unrelated classes need the same behavior, or when you want to compose features. Prefer an interface for plain contracts. Prefer inheritance only for a clear "is-a" relationship.

Limits and gotchas

  • Traits cannot have constructors.
  • Final fields and some static initialisation have limits; check the documentation if you rely on them.
  • Name clashes between trait fields and class fields surface at compile time.
  • Under @CompileStatic everything works, but runtime traits (withTraits) are inherently dynamic.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What can a Groovy trait contain that a classic Java interface cannot?

    Traits can carry state and concrete methods, unlike plain Java interfaces (which can only have constants and default methods without state).
  2. 2. Two traits define move(). A class writes implements Walks, Swims. Which version runs?

    When methods clash, the last trait in the implements list wins, unless the class overrides the method explicitly.
  3. 3. How can you add a trait to one existing object at run time?

    withTraits returns an object that combines the original class with the trait.
  4. 4. What does @SelfType do?

    It states the type the implementing class must satisfy, and the compiler checks it.

Summary

  • A trait is a mixin: methods, abstract methods, fields and properties that classes gain with implements.
  • A class can implement many traits; later traits win conflicts, and Trait.super.method() picks one.
  • Calling super in stacked traits builds layers of behavior.
  • @SelfType states requirements; withTraits applies a trait to a single object at run time.
  • Choose traits for reusable behavior across unrelated classes.

Next: AST Transformations