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 Video Library
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
View Events Video Library
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
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

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Streamlining Your Workflow With the Jenkins HTTP Request Plugin: A Guide to Replacing CURL in Scripts
  • Why "Polyglot Programming" or "Do It Yourself Programming Languages" or "Language Oriented Programming" sucks?
  • Groovy Database Resource Handling
  • Containerize Gradle Apps and Deploy to Kubernetes With JKube Kubernetes Gradle Plugin

Trending

  • Understanding Europe's Cyber Resilience Act and What It Means for You
  • Graph Databases: Unleashing the Power of Relationships
  • CI/CD Tools and Technologies: Unlock the Power of DevOps
  • Three Ways AI Is Reshaping DevSecOps
  1. DZone
  2. Coding
  3. Languages
  4. Groovy 2.3 Introduces Traits

Groovy 2.3 Introduces Traits

Michael Scharhag user avatar by
Michael Scharhag
·
Apr. 20, 14 · Interview
Like (2)
Save
Tweet
Share
23.01K Views

Join the DZone community and get the full member experience.

Join For Free

A few days ago the second beta of Groovy 2.3 got released. One of the major new Groovy 2.3 features are traits. A trait is a reusable set of methods and fields that can be added to one or more classes. A class can be composed out of multiple traits without using multiple inheritance (and therefore avoiding the diamond problem).

Basic usage
The following piece of code shows a basic definition of a trait in Groovy 2.3. 

trait SwimmingAbility {
	def swim() {
		println "swimming.."
	}
}

A trait definition looks very similar to a class definition. This trait defines a single method swim(). We can add this trait to a class using the implements keyword:

class Goldfish implements SwimmingAbility {
	..
}

Now we are able to call the swim() methods on Goldfish objects:

def goldfish = new Goldfish()
goldfish.swim()

So far we could have accomplished the same using inheritance. The difference is that we can add multiple traits to a single class. So let's define another trait:

trait FlyingAbility {
	def fly() {
		println "flying.."
	}
}

We can now create a new class that makes use of both traits:

class Duck implements SwimmingAbility, FlyingAbility {
	..
}

Ducks can swim and fly now: 

def duck = new Duck()
duck.swim()
duck.fly()


this inside traits
Inside traits the this keyword represents the implementing instance. This means you can write the following:

trait FlyingAbility {
	def fly() {
		println "${this.class.name} is flying.."
	}
}

In case of the Duck class from above this will print

Duck is flying..

if we call duck.fly().

A more complex example
Now let's look at an example that shows some more features of Groovy traits 

trait Trader {
	int availableMoney = 0
	private int tradesDone = 0

	def buy(Item item) {
		if (item.price <= availableMoney) {
			availableMoney -= item.price
			tradesDone += 1
			println "${getName()} bought ${item.name}"
		}
	}

	def sell(Item item) {
		..
	}

	abstract String getName()
}

Like Groovy classes traits support properties. Here the property availableMoney will become private and public getter / setter methods will be generated. These methods can be accessed on implementing classes.tradesDone is a private variable that cannot be accessed outside the Trader trait. Within this trait we defined an abstract method getName(). This method has to be implemented by classes that make use of this trait.

Let's create a class that implements our Trader trait:

class Merchant implements Trader {
	String name

	String getName() {
		return this.name
	}
}

A Merchant is now be able to buy items:

def bike = new Item(name: 'big red bike', price: 750)
def paul = new Merchant(name: 'paul')
paul.availableMoney = 2000
paul.buy(bike) // prints "paul bought big red bike"
println paul.availableMoney // 1250


Extending from traits, Overriding and conflict resolution
A trait can inherit functionality from another trait using the extends keyword: 

trait Dealer {
	def getProfit() { ... }
	def deal() { ... }
}

trait CarDealer extends Dealer {
	def deal() { ... }
}

Here the CarDealer trait extends Dealer and overrides the deal() method of Dealer.

Trait methods can also be overwritten in implementing classes:

class OnlineCarDealer implements CarDealer {
	def deal() { ... }
}


If a class implements more than one trait it is possible to create a conflict. That's the case if two or more traits define a method with an identical signature:

trait Car {
	def drive() { ... }
}

trait Bike {
	def drive() { ... }
}

class DrivingThing implements Car, Bike { ... }

In such a situation the last declared trait wins (Bike in this example).

Conclusion
I think traits are a very useful concept and I am happy to see them in Groovy. Other than Groovy mixins traits work at compile time and can therefore be accessed from Java code. For further reading I can recommend the Groovy 2.3 Trait documentation. 

Trait (computer programming) Groovy (programming language)

Published at DZone with permission of Michael Scharhag, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Streamlining Your Workflow With the Jenkins HTTP Request Plugin: A Guide to Replacing CURL in Scripts
  • Why "Polyglot Programming" or "Do It Yourself Programming Languages" or "Language Oriented Programming" sucks?
  • Groovy Database Resource Handling
  • Containerize Gradle Apps and Deploy to Kubernetes With JKube Kubernetes Gradle Plugin

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

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: