Search

Dark theme | Light theme

October 3, 2009

Groovy Goodness: Mixin Functionality to Classes

In a previous blog post we learned how to use Categories to add functionality to existing class. We had to use the use keyword to define a block in which the Category was valid. But we can also add new functionality with the @Mixin compile-time annotation or at runtime with the mixin() method (GDK extension to Class).

 
1
2
3
4
5
6
7
8
9
10
11
class Pirate {
    def talk(text) {
        "Aargh, walk the plank. ${text}"
    }
}
 
// Compile time mixin to Talk class. This add all
// methods from Pirate to Talk.
@Mixin(Pirate) 
class Talk {}
 
assert 'Aargh, walk the plank. Give me a bottle of rum.' == new Talk().talk("Give me a bottle of rum.")
 
1
2
3
4
5
6
7
8
9
10
11
12
13
import org.apache.commons.lang.StringUtils
 
class Parrot {
    static String speak(String text) {
        /Parrot says "$text"/
    }
}
 
// Runtime mixin on String class.
// mixin() is a GDK extension to Class.
String.mixin Parrot, StringUtils
 
assert 'Parrot says "mrhaki"' == 'mrhaki'.speak()
assert 'Groovy is so much...' == 'Groovy is so much fun.'.abbreviate(20// StringUtils mixin.