Table of contents
1.
Introduction
2.
What is Grails?
3.
Traits in Grails
3.1.
Domain Class Traits
3.2.
Controller Traits
3.3.
Interceptor Trait
3.4.
Tag Library Trait
4.
Traits
4.1.
Standard Application of Groovy Traits
4.2.
this Inside Trait
4.3.
One More Example
4.4.
Extending on Traits, Overriding, and Conflict Resolution
5.
Frequently Asked Questions
5.1.
What is Grails?
5.2.
What are the Benefits of Using Grails?
5.3.
What are the Features of Grails?
5.4.
What are Traits?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Grails-Traits

Author Aditya Kumar
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Hey, Ninjas! Do you know Grails? Have you ever heard about Traits in Grails? If not, then don't worry. Coding Ninjas will help you to clear all these doubts.

traits in grails

In this article, we will discuss Traits in Grails. We will discuss what they are. So basically, Trails are nothing but reusable components that we can use to extend the functionality of the different classes. Before moving on to this topic, let us understand what Grails is.
 

What is Grails?

Grails is a framework for high productivity. Grails was originally known as Groovy on Rails when it was first released in 2005, but the name was changed in 2006 due to a disagreement with the inventor of Ruby on Rails.

Grails' purpose was to create a Java web framework by combining existing technologies such as Hibernate and Spring into a single interface. This interface would provide a uniform office atmosphere and the following benefits:

  • Persistent framework documentation
  • Groovy Server Pages Templates (GSP)
  • Dynamic tag libraries are used to create web components.
  • Ajax support that is customizable and extendable.

In the end, the programmers produced a potent web application framework for the Java Virtual Machine built on top of Groovy and Spring Boot.

Traits in Grails

To increase the functionality of various classes, we can utilize traits, which are reusable components that represent a set of methods or behaviors. They are regarded as interfaces since they include state and default implementations.

Grails provides a variety of characteristics that enable access to different Grails artifacts as well as arbitrary Groovy classes that are part of a Grails project. Many of these qualities are automatically added to Grails artifact classes (for example, controllers and taglibs) and are simple to add to other classes.

At build time, Grails artifacts are automatically supplemented with specific features.

Domain Class Traits

Domain Class Traits includes: 

  • grails.web.databinding.WebDataBinding
  • grails.artefact.DomainClass
  • org.grails.datastore.gorm.GormValidateable
  • org.grails.datastore.gorm.GormEntity

Controller Traits

Controller Traits includes: 

  • grails.artefact.controller.RestResponder
  • grails.artefact.AsyncController
  • grails.artefact.Controller
  • grails.artefact.gsp.TagLibraryInvoker

Interceptor Trait

Interceptor Trait include: 

  • grails.artefact.Interceptor

Tag Library Trait

Tag Library Trait include: 

  • grails.artefact.TagLibrary
     
grails traits

Traits

A reusable set of fields and methods that may be added to one or more classes is known as a trait. Multiple traits can be used to form a class without needing multiple Multiple Inheritance in Java.

Standard Application of Groovy Traits

In Groovy 2.3, a trait's fundamental definition is shown in the following line of code.

trait SwordAbility {
  def sword() {
    println "sword swing.."
  }
}

A trait definition resembles a class definition in appearance. This trait establishes a single sword() method. Using the implements keyword, we could add this trait to a class:

class Ragnarok implements SwordAbility {
  ..
}

We can now call the sword() methods on Ragnarok objects:

def ragnarok = new Ragnarok()
ragnarok.sword()

So far, we could have achieved the same result by inheritance. The distinction is that numerous characteristics can be added to a single class. So let us define another characteristic:

trait teachingAbility {
  def teach() {
    println "teaching.."
  }
}

We can now construct a new class that uses both traits:

class human implements SwordAbility, teachingAbility {
  ..
}

Humans can use a sword as well as can teach 

def human = new Human()
human.sword()
human.teach()

this Inside Trait

The implementing instance is represented by this keyword within characteristics. This implies you may write anything like:

trait TeachingAbility {
  def teach() {
    println "${this.class.name} is teaching.."
  }
}

Output: Human is teaching

One More Example

Now consider an example that demonstrates some additional Groovy qualities.

trait Ninja {
 
  int noOfQuesNotSolved = 0
  private int totalQues = 0
 
  def solv(Ques ques) {
    if (ques.resPercent <= noOfQuesSolved) {
      noOfQuesNotSolved -= ques.attemptsQues
      totalQues += 1
      println "${getName()} solved ${ques.name}"
    }
  }
 
  def needToSolv(Ques ques) {
    ..
  }
 
  abstract String getName()
}


Traits, like Groovy classes, support properties. The variable noOfQuesNotSolved will become private in this case, and public getter/setter methods will be produced. These methods are available for implementing classes. totalQues is a private variable that is not accessible outside of the Ninja trait. We developed an abstract method getName under this trait(). Classes that make use of this trait must implement this method.

Let's make a class that uses our Ninja traits:

class CodingNinja implements Ninjas {
   
  String name
 
  String getName() {
    return this.name
  }
}

A CodingNinjas can solve these problems:

def ques1 = new Ques(name: 'Anagram of a String', attemptsQues: 10)
def Aditya = new CodingNinja(name: 'Aditya')
 
Aditya.noOfQuesNotSolved = 300
Aditya.solv(quest1) // prints "Aditya solved Anagram of a String"
 
println Aditya.noOfQuestNotSolved // 290 becuase Aditya attempted 10 questions

Extending on Traits, Overriding, and Conflict Resolution

Using the extends keyword, a trait can inherit features from another trait:

trait Coder {
  def getQues() { ... }
  def solved() { ... }
}
 
trait CompetitiveCoders extends Coder {
  def solved() { ... }
}

In this case, the CompetitiveCoders trait extends Coder and overrides the solved() function.

In implementing classes, trait methods can also be overriden:

class NinjaCoders implements CompetiveCoders {
  def solved() { ... }
}


If a class implements more than one characteristic, a conflict may arise. This is true if two or more characteristics specify a method with the same signature:

trait Ques {
  def solvingQues() { ... }
}
 
trait StringProb {
  def solvingQues() { ... }
}
 
class DSATopics implements Ques, StringProb { ... }

In such a case, the last claimed trait is overcome (StringProb in this example).

Frequently Asked Questions

What is Grails?

Grails is a free and open-source web application framework that makes use of the Apache Groovy programming language (which is, in return, based on the Java platform). By adhering to the "code by convention" concept, it is meant to be a high-productivity framework.

What are the Benefits of Using Grails?

The most common benefits of using Grails are Reusability, Low maintenance, Cost Saving, Faster time to Market, and many more.

What are the Features of Grails?

Following are the features of the Grails Groovy Lineage, Spring Boot Foundation, Built-in Testing framework, Plugin Library, and Pragmatic Strategy.

What are Traits?

A trait can have default method implementations, and a type can implement many traits simultaneously. This enables some form of multiple inheritances.

Conclusion

In this article, we learned about traits in Grails. We learned what they are and how they work using small snippets.  After reading about Grails Traits, do you feel you need more time to read/explore more articles on Ruby on Grails? Don't worry; Coding Ninjas has you covered. 

Refer to our Guided Path on Code studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! 

Happy Coding!

Live masterclass