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]
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With