Groovy Goodness: Use Constructor as Method Pointer
Join the DZone community and get the full member experience.
Join For FreeIn Java 8 we can create a constructor reference. We must use the syntax Class::new
and we get a constructor reference. This syntax is not supported in Groovy, but we can use the method pointer or reference syntax .&
to turn a method into a closure. We can even turn a constructor into a closure and use it everywhere where closures are allowed.
In the following sample code we have a User
class with some properties. Via the User.metaClass
we can get a reference to the methodinvokeConstructor
and turn it into a method closure:
@groovy.transform.Immutable class User { String name int age } // Initial list with user defined // using a map or Object array. def userList = [ // User defined as map, keys // are properties of User class. [name: 'mrhaki', age: 41], // Object array with name and // age properties for User class. ['john', 30] as Object[] ] // Create constructor reference. // Result is a closure we can use in our code. def createUser = User.metaClass.&invokeConstructor // Invoke the collect method with our // constructor reference. At the end // all elements of the userList // are converted to new User objects. def users = userList.collect(createUser) assert users.name == ['mrhaki', 'john'] assert users.age == [41, 30]
Code written with Groovy 2.4.1.
Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Integrate Cucumber in Playwright With Java
-
Why I Prefer Trunk-Based Development
-
A React Frontend With Go/Gin/Gorm Backend in One Project
-
A Deep Dive Into the Differences Between Kafka and Pulsar
Comments