Groovy等效于Java 8 ::(双冒号)运算符 [英] Groovy equivalent of Java 8 :: (double colon) operator

查看:301
本文介绍了Groovy等效于Java 8 ::(双冒号)运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相当于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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆