Over a million developers have joined DZone.

Groovy Goodness: Identity Closure

DZone's Guide to

Groovy Goodness: Identity Closure

Here's a look at how Groovy handles identity functions, or rather, identity closures.

· Java Zone ·
Free Resource

Bring content to any platform with the open-source BloomReach CMS. Try for free.

In functional programming, we have the concept of an identity function. An identity function returns the same result as the input of the function. Groovy has a lot of functional paradigms, including an identity function. Of course, in Groovy's case, it is an identity closure. It is defined as a constant in the Closure class: Closure.IDENTITY. If we use this closure, we get the same result as the argument we provide.

In the following example, we first create our own identity closure. Next, we use the built-in Closure.IDENTITY closure:

// Identity closure should return the same value
// as the input.
def identity = { a -> a }
assert identity(42) == 42
assert identity('Groovy rocks!') == 'Groovy rocks!'

// Groovy adds constant Closure.IDENTITY to 
// represent an identity closure:
assert Closure.IDENTITY('Groovy rocks!') == 'Groovy rocks!'
assert Closure.IDENTITY(['Groovy', 'is', 'gr8']) == ['Groovy', 'is', 'gr8']
assert Closure.IDENTITY(a: 1, b: 2, c: 3) == [a: 1, b: 2, c: 3]

// With static import we can reference
// the constant identity closure as well.
import static groovy.lang.Closure.IDENTITY
assert IDENTITY(42) == 42

// Can be useful to create a 
// Closure for constant values.
def theAnswer = IDENTITY.curry(42)
assert theAnswer() == 42

// Useful default for Closure method argument.
// Without default for the transform argument, 
// we have to pass two arguments.  
// Now the method accepts a single argument as well.
def transformString(String value, Closure transform = Closure.IDENTITY) {

// Use default transform value (Closure.IDENTITY).
assert transformString('hubert') == 'hubert'

// Use custom transform Closure argument.
assert transformString('mrhaki') { s -> s.toUpperCase() } == 'MRHAKI'

Written with Groovy 2.4.7.

BloomReach CMS: the API-first CMS of the future. Open-source & enterprise-grade. - As a Java developer, you will feel at home using Maven builds and your favorite IDE (e.g. Eclipse or IntelliJ) and continuous integration server (e.g. Jenkins). Manage your Java objects using Spring Framework, write your templates in JSP or Freemarker. Try for free.

closure ,java ,groovy ,functional programming ,identity

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}