Groovy 2.3 Traits Example

// groovy 2.3.0 traits
import groovy.transform.ForceOverride
import groovy.transform.*
// make a trait to hold a property
trait Named {
String name;
// tell compiler to use this toString() rather than class toString()
@ForceOverride // don't forget the import stmt !
String toString(){return "hi "+name}
// make an action trait to do something
trait Quacks{
String quack() {'Quack!'}
// make a class
class Animal{}
// declare a var with more than one trait
def ani = new Animal().withTraits Named, Quacks
// give it a name'Daffy'
assert'Daffy' // bingo !
// do it again using the groovy AS runtime trait coercion 
def ani2 = new Animal() as Named'Fred'
// what do we have ?
println 'name:'+ani2 // prints name:hi Fred
println 'name:' // prints name:Fred
println 'name:' // prints name:Fred
// let's see how to sort an array list of objects
@Sortable // makes a Comparable method for several keys
class Person{
 // sort order of keys is by property sequence order surname,firstname, etc
 String surname
 String firstname
} // end of class
def list=[]
def p1 = new Person('surname':'jones', 'firstname':'fred')
def p2 = new Person('surname':'baker', 'firstname':'marge')
def p3 = new Person('surname':'frost', 'firstname':'jack')
list << p1
list << p2
list << p3
list.each{println it.surname.toString();}
println "--- the end ---"
// --- the end ---

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s