Groovy equivalent for Java 8 Lambda Expression

I have this Java interface with only one method.

// Java Interface public interface AuditorAware { Auditor getCurrentAuditor(); } 

I used the Java 8 Lambda expression to create an AuditorAware feel like this.

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

I am trying to write the above Java implementation in Groovy.

I see that there are many ways to implement interfaces in groovy, as shown in this Groovy interface implementation methods .

I implemented the above Java code up to the groovy equivalent using the implementation interfaces with the map, as shown in the above documentation.

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

But the implementation of interfaces with the closure method looks more concise, as shown in the sample documentation. However, when I try to implement it as follows, IntelliJ shows errors saying Undefined code .

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

How can I change the Java 8 lambda implementation to the groovy equivalent using the "implement interfaces with closure" method?

+6
source share
2 answers

As Dylan Bijnagte commented, the following code worked.

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

Section Parameter Notes Groovy Documentation Closing explains this.

+4
source

You can use the .& Operator to get a reference to a method:

 class Auditor { String name } interface AuditorAware { Auditor getCurrentAuditor() } class AuditorContextHolder { static getAuditor() { new Auditor(name: "joe") } } AuditorAware currentAuditor() { AuditorContextHolder.&getAuditor } assert currentAuditor().currentAuditor.name == "joe" 

In Java 8, you can use links :: for method references:

  AuditorAware currentAuditor() { return AuditorContextHolder::getAuditor; } 
+3
source

Source: https://habr.com/ru/post/976955/


All Articles