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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With