Skip to main content
Blog

Groovy closures for now – no Java 8 lambdas just yet

By 20 juni 2014januari 30th, 2017No Comments

Java 8 is featuring lambdas, which are similar to a construction Groovy has already for some time: closures.

In Groovy we could already do this:

def list = ['a', 'b', 'c']
print list.collect { it.toUpperCase() }
// [A, B, C]

where { it.toUpperCase() } is the closure.

In Java 8 we can achieve the same functionality now in a concise way.

list.stream().map( s -> s.toUpperCase() )

Groovy’s strengths has always been the possibility to just copy ’n paste Java code and it just works, but it seems that this  will not work as of yet for a few Java 8 syntax constructs, such as:

  • reference methods
  • lambdas
  • default methods in interfaces
  • repeated annotations
  • annotations on types

The current decision about lambdas, according to the notes of the Groovy DevCon #10 meetup, right after GR8Conf Europe 2014 earlier this month, is that the Java 8 lambda syntax for now won’t be adopted.

If ever we were to support the syntax Java lambdas, we should back them with closure.
But it’s confusing to have two different syntaxes for the same concept, as users will always wonder when to use one construct over the other, for which benefits or drawbacks.

Currently, beside the Java copy’n paste compatibility, there’s no reason to support the Java 8 lambda notation, as the Groovy closure to SAM type (Single Abstract Method) coercion mechanism already allows to use Groovy closures wherever a Java 8 lambda could be used.

Groovy closures already offer more capabilities than Java 8 lambdas and can be used in more contexts so far.

For now, if I would have to choose one syntax – I’m quite fond of Groovy syntax compactness 🙂