Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hidden features of Groovy?

Tags:

groovy

Using the spread-dot operator

def animals = ['ant', 'buffalo', 'canary', 'dog']
assert animals.size() == 4
assert animals*.size() == [3, 7, 6, 3]

This is a shortcut for animals.collect { it.size() }.


The with method allows to turn this:

 myObj1.setValue(10)
 otherObj.setTitle(myObj1.getName())
 myObj1.setMode(Obj1.MODE_NORMAL)

into this

 myObj1.with {
    value = 10
    otherObj.title = name
    mode = MODE_NORMAL
 }

Using hashes as pseudo-objects.

def x = [foo:1, bar:{-> println "Hello, world!"}]
x.foo
x.bar()

Combined with duck typing, you can go a long way with this approach. Don't even need to whip out the "as" operator.


Anyone know about Elvis?

def d = "hello";
def obj = null;

def obj2 = obj ?: d;   // sets obj2 to default
obj = "world"

def obj3 = obj ?: d;  // sets obj3 to obj (since it's non-null)

Finding out what methods are on an object is as easy as asking the metaClass:

"foo".metaClass.methods.name.sort().unique()

prints:

["charAt", "codePointAt", "codePointBefore", "codePointCount", "compareTo",
 "compareToIgnoreCase", "concat", "contains", "contentEquals", "copyValueOf", 
 "endsWith", "equals", "equalsIgnoreCase", "format", "getBytes", "getChars", 
 "getClass", "hashCode", "indexOf", "intern", "lastIndexOf", "length", "matches", 
 "notify", "notifyAll", "offsetByCodePoints", "regionMatches", "replace", 
 "replaceAll", "replaceFirst", "split", "startsWith", "subSequence", "substring", 
 "toCharArray", "toLowerCase", "toString", "toUpperCase", "trim", "valueOf", "wait"]

To intercept missing static methods use the following

 Foo {
    static A() { println "I'm A"}

     static $static_methodMissing(String name, args) {
        println "Missing static $name"
     }
 }

Foo.A()  //prints "I'm A"
Foo.B()  //prints "Missing static B"

-Ken


Destructuring

It might be called something else in Groovy; it's called destructuring in clojure. You'll never believe how handy it can come.

def list = [1, 'bla', false]
def (num, str, bool) = list
assert num == 1
assert str == 'bla'
assert !bool