相当于 Java 8 ::(双冒号)运算符的 Groovy [英] Groovy equivalent of Java 8 :: (double colon) operator
问题描述
Java 8 的等价物是什么 :: (双冒号运算符) 在 Groovy 中?
What would the equivalent to Java 8 :: (double colon operator) in Groovy?
我正在尝试在 groovy https://github.com/bytefish/PgBulkInsert
I'm trying to translate this example in groovy https://github.com/bytefish/PgBulkInsert
但是映射部分的工作方式与 Java 8 不同:
But the mapping part doesn't work the same way as Java 8:
public PersonBulkInserter() {
super("sample", "unit_test");
mapString("first_name", Person::getFirstName);
mapString("last_name", Person::getLastName);
mapDate("birth_date", Person::getBirthDate);
}
推荐答案
Groovy 并没有真正的实例分离实例方法引用(Yet.请参阅 Wavyx 对此答案的评论.),所以你必须用闭包来伪造它.在 Java 8 中使用实例方法引用语法时,您实际上是在设置 lambda 的等效项,它期望调用实例作为其第一个(在本例中,仅是)参数.
Groovy doesn't really have instance-divorced instance-method references ( Yet. See Wavyx's comment on this answer.), so instead you have to fake it with closures. When using instance-method reference syntax in Java 8, you are really setting up the equivalent of a lambda that expects the invoking instance as its first (in this case, only) argument.
因此,为了在 Groovy 中获得相同的效果,我们必须创建一个使用默认 it
参数作为调用实例的闭包.像这样:
Thus, to get the same effect in Groovy we have to create a closure that uses the default it
argument as the invoking 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)
}
注意这里使用了 Groovy 属性符号,并且有必要将 Closure
强制转换为 mapString()<所期望的
@FunctionalInterface
类型/code> 或 mapDate()
方法.
Notice the use of Groovy property notation here, and that it is necessary to cast the Closure
to the @FunctionalInterface
type expected by the mapString()
or mapDate()
method.
这篇关于相当于 Java 8 ::(双冒号)运算符的 Groovy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!