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

后端 未结 2 1113
深忆病人
深忆病人 2021-01-04 02:52

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

相关标签:
2条回答
  • 2021-01-04 02:53

    As of Groovy 3 (beta), groovy now has support for java 8 colon syntax (and more).

    So the example you have will work exactly the same in groovy.

    0 讨论(0)
  • 2021-01-04 02:54

    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.

    0 讨论(0)
提交回复
热议问题