Groovy 中的 Java 8::( double colon operator ) 相当于什么?
我正在尝试用 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 的等效项,该 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()< 所期望的
或 @FunctionalInterface
类型mapDate()
方法。
关于Java 8::(双冒号)运算符的 Groovy 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41398751/