blendmaster
blendmaster

Reputation: 197

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].

Upvotes: 5

Views: 1113

Answers (1)

Arturo Herrero
Arturo Herrero

Reputation: 13122

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

Upvotes: 6

Related Questions