logo image

Extra Keywords in Groovy and their usage

There are four extra keywords that groovy adds apart from the Java's list they are the following 1. as 2. def 3. in 4. trait

1. 'as' Keyword

as keyword is used for multiple purposes

1. To change type of Objets

using as key word you can change type of any Object, In the following example I have changes a String to Integer by using as keyword

String ageInString = '25'	
int age = ageInString as Integer	
print age

2. To give alias names for imports

You can use 'as' keyword to assign a alias name for an import as shown in following example

import java.lang.Math as m

class GroovyAsKeyword {
	static void main(String[] args) {
		println m.sqrt(16);

2. 'def' Keyword

def keyword is used to define type for a variable. If you use def then you are not restricting the variable to be a specific type, you can assign any type. This is equivalent to defining a Object type in Java

def name = 'foo'
def age = 25

3. 'in' Keyword

In can be used to check whether or not an item exist in a Collection

def names = ['foo1', 'foo2', 'foo3']
if('foo1' in names) {
	print 'Yes'

4. 'trait' Keyword

'trait' in groovy is like an Interface with default methods and also state. Using traits you can add behaviour to classes You can create a trait as shown in following code

trait DriveAbility {                           
        String drive() { 'Driving' }

Then you can add this behaviour for classes just by implementing this trait

class Volvo implements  DriveAbility{


Now the class volvo gets the drive() behaviour