Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 457
Curtis Allen Avatar asked Dec 04 '22 03:12

Curtis Allen


1 Answers

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
    }
}
like image 185
Curtis Allen Avatar answered Dec 17 '22 07:12

Curtis Allen