Java 8 Lambda Expression的Groovy等价物

The*_*ect 6 java groovy lambda closures java-8

我只有一个方法有这个Java接口.

// Java Interface
public interface AuditorAware {
    Auditor getCurrentAuditor();
}
Run Code Online (Sandbox Code Playgroud)

我正在使用Java 8 Lambda表达式来创建AuditorAware如下的内容.

// Java 8 Lambda to create instance of AuditorAware
public AuditorAware currentAuditor() {
    return () -> AuditorContextHolder.getAuditor();
}
Run Code Online (Sandbox Code Playgroud)

我试图在Groovy中编写Java实现.

我看到有很多方法可以在groovy中实现接口,如Groovy实现接口文档的方法所示.

我已经在Java代码上实现了groovy等效,通过使用带有map的实现接口,如上面提到的文档中所示.

// Groovy Equivalent by "implement interfaces with a map" method
AuditorAware currentAuditor() {
    [getCurrentAuditor: AuditorContextHolder.auditor] as AuditorAware
}
Run Code Online (Sandbox Code Playgroud)

但是,如文档示例所示,使用闭包方法实现接口似乎更简洁.但是,当我尝试按如下方式实现时,IntelliJ显示错误代码模糊代码块.

// Groovy Equivalent by "implement interfaces with a closure" method ???
AuditorAware currentAuditor() {
    {AuditorContextHolder.auditor} as AuditorAware
}
Run Code Online (Sandbox Code Playgroud)

如何通过使用"使用闭包实现接口"方法将Java 8 lambda实现更改为groovy等效?

The*_*ect 4

正如Dylan Bijnagte所评论的,以下代码有效。

// Groovy Equivalent by "implement interfaces with a closure" method 
AuditorAware currentAuditor() {
    { -> AuditorContextHolder.auditor} as AuditorAware
}
Run Code Online (Sandbox Code Playgroud)

Groovy Closure文档的参数注释部分解释了这一点。