DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • How Web3 Is Driving Social and Financial Empowerment
  • Send Email Using Spring Boot (SMTP Integration)
  • RAML vs. OAS: Which Is the Best API Specification for Your Project?
  • Is Podman a Drop-in Replacement for Docker?

Trending

  • How Web3 Is Driving Social and Financial Empowerment
  • Send Email Using Spring Boot (SMTP Integration)
  • RAML vs. OAS: Which Is the Best API Specification for Your Project?
  • Is Podman a Drop-in Replacement for Docker?
  1. DZone
  2. Coding
  3. Languages
  4. Groovy Goodness: Chaining Traits

Groovy Goodness: Chaining Traits

Hubert Klein Ikkink user avatar by
Hubert Klein Ikkink
·
May. 24, 14 · Interview
Like (0)
Save
Tweet
Share
4.09K Views

Join the DZone community and get the full member experience.

Join For Free

Since Groovy 2.3 we can use traits in our code. We can even chain traits using the so called stackable traits feature. This means a trait can delegate to another trait or we can stop the delegation base based on a condition. Inside the method implementation of a trait we can use super.method to delegate to the next trait (if available) in the chain. If we don't use super.method the chain is stopped.

In the following sample code we want to transform a String input value to an output value. We implement the transform method from theTransformer interface using different traits. For example the Upper trait will make the input value upper cased and invokes super.transform to delegate to the next trait. Then we write new classes that implement the traits. The order of the traits determines the chain. The last declared trait is invoked first then the traits defined from right to left are invoked.

/** 
 * Simple interface with one method to 
 * transform a String value.
 */
interface Transformer {
    String transform(String input)
}

/** Default trait will return the input value unchanged. */
trait DefaultTransformer implements Transformer {
    String transform(String input) {
        input
    }
}

/** Transform the String value to upper case */
trait Upper implements Transformer {
    String transform(String input) {
        super.transform(input.toUpperCase())
    }
}

/** Remove 'mr' from input String value. */
trait Filter implements Transformer {
    String transform(String input) {
        super.transform(input - 'mr')
    }
}

/**
 * Simple class uses three traits. The value property get method
 * returns the transformed value.
 */
class StringTransformer implements DefaultTransformer, Upper, Filter {
    String value
    String getValue() { transform(value) }
}

// Create StringTransformer instance.
def transformer = new StringTransformer(value: 'mrhaki')

assert transformer.value == 'HAKI' 


// Use same traits, but in different order.
class OtherStringTransformer implements DefaultTransformer, Filter, Upper {
    String value
    String getValue() { transform(value) }
}

// Create OtherStringTransformer instance.
def otherTransformer = new OtherStringTransformer(value: 'mrhaki')

// The Filter trait cannot find 'mr', 
// because the String value is already in
// upper case after the Upper trait.
assert otherTransformer.value == 'MRHAKI'


/** Only chain input values smaller than 5 characters. */
trait SmallFilter implements Transformer {
    String transform(String input) {
        if (input.size() < 5) {
            super.transform(input)
        } else {
            ''
        }
    }
}

class SmallStringTransformer implements DefaultTransformer, Upper, SmallFilter {
    String value
    String getValue() { transform(value) }
}

def smallTransformer = new SmallStringTransformer(value: 'mrhaki')
assert smallTransformer.value == ''

smallTransformer.value = 'haki'
assert smallTransformer.value == 'HAKI'

Code written with Groovy 2.3.1.

Trait (computer programming) Groovy (programming language)

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • How Web3 Is Driving Social and Financial Empowerment
  • Send Email Using Spring Boot (SMTP Integration)
  • RAML vs. OAS: Which Is the Best API Specification for Your Project?
  • Is Podman a Drop-in Replacement for Docker?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: