Over a million developers have joined DZone.

Mixing Java Functions and Groovy Closures

DZone's Guide to

Mixing Java Functions and Groovy Closures

When mixing Java and Groovy, the time might come when you want to dip into Java's functional features, but while using Groovy's syntax. Enter closures.

· Java Zone
Free Resource

Just released, a free O’Reilly book on Reactive Microsystems: The Evolution of Microservices at Scale. Brought to you in partnership with Lightbend.

With Java 8 offering functional features, the question comes to mind, "How and why Java functions can be used in Groovy?"

In many ways, closures and functions more or less offer the same functionality. Groovy has support for functions, but not for lambdas. The syntax conflicts because the arrow symbol is already used in Groovy. In what way can the two, Java functions and groovy closures, be used together?

The first example, a Java functional interface is implemented with a Closure in Groovy:

List list = [1,4,2,3,7,4]
BiFunction greaterThen_java = { 
    Integer a, Integer b ->
    a > b ? true : false
assert greaterThen_java.apply(1, 2) == false

This is really the same as the following in Groovy:

def greaterThen_groovy = { Integer a, Integer b ->
    a > b ? true : false
assert greaterThen_groovy.call(1 ,2) == false

Except for the typing information, which is ignored anyway, the two examples are semantically and syntactically almost identical.

Some Java methods take functions as arguments. For example, Collection’s removeIf method:

Predicate greaterThen2 = { a ->
    a > 2 ? true : false
assert list.size() == 2 && list[0] == 1 && list[1] == 2

In the above example, the predicate is implemented with a closure and passed to the Java method removeIf, which executes the predicate. Groovy and Java syntax and functionality nicely mix together.

Unfortunately, the lambda syntax isn’t supported in Groovy. A closure will do, however. Take the following example:

def min = { Integer a, Integer b -> 
    a < b ? a : b 
Integer result = list.stream().reduce( min ).get() 
assert result == 1

Instead of using Java syntax for the reduce method, we pass a closure with the correct input parameters. The Java streams functionality can then be used as usual. If you keep in mind when to use functions and closures, both Java and Groovy's functional features can be used together, creating an even more powerful combination.

Strategies and techniques for building scalable and resilient microservices to refactor a monolithic application step-by-step, a free O'Reilly book. Brought to you in partnership with Lightbend.

java ,functional interface ,groovy ,closures ,lambda expressions

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}