Alternate Constructors in Groovy

14 September 2017

There are a variety of ways to construct objects in Groovy. We were looking for something more dynamic where we could parameterize the object to be constructed.

We found a couple different things that worked to instantiate an object:

import groovy.transform.*

@ToString
class MyClass {
    String first
    String last
}

def map = [first: 'f', last: 'l']

// instantiate from literal class reference
println new MyClass(map)
println MyClass.newInstance(map)
println (map as MyClass)
println map.asType(MyClass)

// instantiate from a variable reference the class
def clazz = MyClass

println map.asType(clazz)
// println (map as clazz) // 'as' operator doesn't like 'clazz' variable
println clazz.newInstance(map)


Groovy Map Minus

06 June 2017

Groovy is relatively intuitive for me: I can usually guess a method or operator and find it works as I had guessed.

Removing a key/value by the key from a Map conveniently eludes me though. I always guess that I should be able to minus a key from a Map to produce a new Map with that entry /value removed. That doesn’t work, so I needed to invent my own. I still not sure how to practically apply it everywhere though, or if it’s even worthwhile. In practice, I always end up writing the findAll inline.

@Category(Map)
class MapMinus {
    Map minus(Collection keys) {
        this.findAll { k, v -> ! (k in keys) }
    }
    Map minus(Object key) {
        this - [key]
    }
}

use (MapMinus) {
    assert [b: 2, c: 3,] == [a: 1, b: 2, c: 3,] - 'a'
    assert [b: 2, c: 3,] == [a: 1, b: 2, c: 3,] - ['a']

}


All the Posts

September 2017

June 2017