Groovy equivalent of Java 8 :: operator (double colon)

What is equivalent to Java 8 :: ( double colon operator ) in Groovy?

I am trying to translate this example into groovy https://github.com/bytefish/PgBulkInsert

But the display part does not work the same as Java 8:

public PersonBulkInserter() { super("sample", "unit_test"); mapString("first_name", Person::getFirstName); mapString("last_name", Person::getLastName); mapDate("birth_date", Person::getBirthDate); } 
+12
source share
2 answers

Groovy actually has no reference to the instance method with instance diversity (EDIT: Bye. See Wavyx's comment on this answer.), So you should fake it with closures instead. When using the reference syntax of the instance method in Java 8, you really set up the equivalent lambda, which expects the calling instance to be the first (in this case, only) argument.

So in order to get the same effect in Groovy, we need to create a closure that uses the default argument it as the calling instance. Like this:

 PersonBulkInserter() { super("sample", "unit_test") mapString("first_name", { it.firstName } as Function) mapString("last_name", { it.lastName } as Function) mapDate("birth_date", { it.birthDate } as Function) } 

Note the use of Groovy property notation here, and that you must use the Closure type for @FunctionalInterface expected by the mapString() or mapDate() method.

+12
source

Starting with Groovy 3 (beta), groovy now has support for java 8 ( or more ) colon syntax.

Thus, your example will work exactly the same in Groovy.

+3
source

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


All Articles