Themes

Select a theme

Groovy : simplifying SAM type as closures

A SAM type is a type which defines a single abstract method. It includes functional interfaces and Abstract classes with single abstract method .

Functional interface: An Interface which permits only single Abstract method excluding the default methods. Functional Interface was introduced in Java 8. For compile time validations, @FunctionalInterface was introduced.

        interface Predicate<T> {
            boolean test(T obj)
        }

Abstract classes with single abstract method:

public class predicateImpl  implements predicate<String>{
      @override
      boolean test(String obj){
       return obj.contains('G')
      }
}

Groovy closures are very powerful. They can be coerced to a ` AST using as operator. Since version 2.2.0 , as ` operator is optional.

@param source the list
@param predicate the functional interface
public <T> List<T> collect(List<T> source, Predicate<T> predicate) {
    source.findAll { predicate.test(it) }
}

The above use case might seem alien at first. But once we go through a few examples, it would be clear that it is the most common use case used in most operations in groovy. Implementing such a use case in groovy would be like

    collect(['Java','Groovy'], { it.contains 'G'} as Predicate) -(1)
    //or 
    collect(['Java','Groovy'], { it.contains 'G }) // version 2.2.0 -(2)

In the (2)nd case , the 2nd parameter is closure and it is coerced to an AST. so we can use the closure syntax for the method calls i.e. put the closure outside of the parenthesis which improves the readability of code and simplifies the syntax

collect(['Java','Groovy']) { it.contains 'G }

looking closely to the above code, It is same syntax used for the collect method for collections such as

[1,2,3,4,5].collect([]){ it*it }

If you have any feedback, let me know in the comments below and don't forget to give a thumbs up.