groovy Traits Basic Usage


Example

A trait is a reusable set of methods and fields that can be added to one or more classes.

trait BarkingAbility {
    String bark(){ "I'm barking!!" }
}

They can be used like normal interfaces, using implements keyword:

class Dog implements BarkingAbility {}
def d = new Dog()
assert d.bark() = "I'm barking!!"

Also they can be used to implement multiple inheritance (avoiding diamond issue).

Dogs can scratch his head, so:

trait ScratchingAbility {
    String scratch() { "I'm scratching my head!!" }
}

class Dog implements BarkingAbility, ScratchingAbility {}
def d = new Dog()
assert d.bark() = "I'm barking!!"
assert d.scratch() = "I'm scratching my head!!"