How to convert Groovy class constructor to Closure?

So Groovy has this relatively convenient syntax for converting methods to locks, for example.

[1,2,3].each { println it }

// is equivalent to

[1,2,3].each this.&println

But how to convert a Constructor class like

[1,2,3].collect { new Thing( it ) }

// is equivalent to

[1,2,3].collect ????

Groovy reflection has a Thing.constructorschecklist, but I can't figure out where to put the ampersand in Thing.constructors[0].

+5
source share
1 answer

You can use invokeConstructorthe metaClass method , which calls the constructor for the given arguments.

class Thing {
    Thing(Integer num) { this.num = num }
    Integer num
}

[1,2,3].collect Thing.metaClass.&invokeConstructor
+6
source

All Articles