Skip to content

Instantly share code, notes, and snippets.

@dmahapatro
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmahapatro/84415e7bdba04a1c8ed6 to your computer and use it in GitHub Desktop.
Save dmahapatro/84415e7bdba04a1c8ed6 to your computer and use it in GitHub Desktop.
Use of @trait AST in Groovy without creating a trait
/* Using @Trait AST provided by Groovy 2.3 to convert a pre-existing class to a Trait */
import groovy.transform.Trait
//Declare the class as a Trait by using the Trait
//without creating a new trait
@Trait
class FlyingAbility {
String fly() { "${this.name}: I can fly (wink)" }
}
class Hero {
//is a living "homo sapien"
}
class SuperHero extends Hero {
String name
String power
String hasPower() { "I blow up things with my $power" }
void showPower() { println "${this.name}: ${hasPower()}" }
}
//Instead of creating a new trait with FlyingAbility We can implement Super Hero with flying ability
//from the class FlyingAbility which has @Trait annotated. The class is transformed to Trait already.
//Cannot extend FlyingAbility (multiple inheritance on class not allowed)
class FlyingSuperHero extends SuperHero implements FlyingAbility { }
class Avengers {
def ironMan = new FlyingSuperHero(name: "IronMan", power: 'attitude')
def hulk = new FlyingSuperHero(name: "Hulk", power: 'thrust')
def captainAmerica = new SuperHero (name: "Captain America", power: 'shield')
void showPowers() {
[ironMan, hulk, captainAmerica]*.showPower()
}
void canFly() {
[ironMan, hulk, captainAmerica].each { hero ->
try{
println hero.fly()
} catch( groovy.lang.MissingMethodException m ) {
println "${hero.name} has no flying ability"
}
}
}
}
def avengers = new Avengers()
avengers.showPowers() //Show powers
avengers.canFly() //Check flying ability
//Add flying powers to Captain America while saving the world (at runtime)
def captainAmericaOnSteroids = avengers.captainAmerica as FlyingAbility
println captainAmericaOnSteroids.fly()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment