在 Groovy 1.x 中写入 Java8 Lambda

Write Java8 Lambdas in Groovy 1.x

有没有办法在groovy1.x中编写Java8 lambda表达式? 我知道 groovy 2.3.x 支持来自此 post 的 Java8 lambda 表达式,但是是否可以在 groovy 中编写 Java 8 lambda ? 我有一些正在使用 Spock 测试的 Java 8 代码,但我的项目在使用 groovy 1.x 时卡住了。

否,建议 Groovy 3.0

不在最新的 2.3/2.4.1 中:

根据您发布的link,这些评论中已经回答了。您可以尝试使用 Closures 代替。

基于官方 Groovy 文档:

Groovy 2.3 doesn’t support the new syntax constructs offered by Java 8 (such as lambdas, method references, default methods in interfaces, etc), but you can very well already use the new APIs offered by JDK 8, and even use Groovy closures in lieu of Java 8 lambdas.

您正在使用更旧的 Groovy 版本,如果 2.3 不支持它,您的版本将不支持。

来源:http://www.groovy-lang.org/releasenotes/groovy-2.3.html

2.4 中未提及任何内容(http://www.groovy-lang.org/releasenotes/groovy-2.4.html)

事实证明,您可以使用 groovy 1.x 中的 as 关键字将 groovy Closure 转换为 java 8 lambda .
考虑以下 java class

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

从 Spock 测试(在 groovy 中)我们可以写出

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