Groovy等效于Java 8 ::(双冒号)运算符 [英] Groovy equivalent of Java 8 :: (double colon) operator
问题描述
相当于Java 8 ::(双冒号运算符)在Groovy中?
我正在尝试用groovy翻译此示例 https://github.com/bytefish/PgBulkInsert
但是映射部分的工作方式与Java 8不同:
public PersonBulkInserter() {
super("sample", "unit_test");
mapString("first_name", Person::getFirstName);
mapString("last_name", Person::getLastName);
mapDate("birth_date", Person::getBirthDate);
}
Groovy确实没有实例分离的实例方法引用(还.请参见Wavyx对这个答案的评论.) ,因此您必须使用闭包来伪造它.在Java 8中使用实例方法引用语法时,您实际上是在设置与希望将调用实例作为其第一个(在此例中,仅是)参数的lambda等效的对象.
因此,要在Groovy中获得相同的效果,我们必须创建一个使用默认it
参数作为调用实例的闭包.像这样:
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()
或mapDate()
方法所期望的@FunctionalInterface
类型.
What would the equivalent to Java 8 :: (double colon operator) in Groovy?
I'm trying to translate this example in groovy https://github.com/bytefish/PgBulkInsert
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 doesn't really have instance-divorced instance-method references (EDIT: 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.
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)
}
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.
这篇关于Groovy等效于Java 8 ::(双冒号)运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!