Search code examples
javagroovylambdajava-8spock

Write Java8 Lambdas in Groovy 1.x


Is there a way to write Java8 lambda expressions in groovy 1.x? I know that groovy 2.3.x supports Java8 lambda expressions from this post but is it possible to write a Java 8 lambda in groovy? I have some Java 8 code that I'm testing with Spock, but my project is stuck using groovy 1.x.


Solution

  • Turns out you can use the as keyword in groovy 1.x to cast a groovy Closure to a java 8 lambda.
    Consider the following java class

    public class Foo {
        public static boolean getBar(Predicate<String> predicate) {
            return predicate.test("hello");
        }
    }
    

    From a Spock Test (in groovy) we can write

    class FooSpecTest extends Specification {
        def "test foo"() {
            when:
            boolean result = Foo.getBar({x -> x.contains("blah")} as Predicate<String>)
            then:
            result == true
        }
    }