Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a Groovy class constructor into a Closure?

So Groovy has this relatively handy syntax to convert methods into closures, e.g.

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

// is equivalent to

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

But how do I convert a class Constructor, e.g

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

// is equivalent to

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

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

like image 861
Steven Ruppert Avatar asked May 22 '12 16:05

Steven Ruppert


1 Answers

You can use invokeConstructor metaClass method that invokes a constructor for the given arguments.

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

[1,2,3].collect Thing.metaClass.&invokeConstructor
like image 94
Arturo Herrero Avatar answered Nov 02 '22 15:11

Arturo Herrero