请检查下面的示例 JUnit 类:
import groovy.transform.CompileStatic
import org.apache.commons.lang3.tuple.Pair
import org.junit.Test
import java.util.function.Function
@CompileStatic
class GroovyFunctionTypeInferenceTest {
@Test
void functionWithoutPairTest() {
// some function that operates on list and returns an element of this list
Function<List<String>, String> function =
{ List<Pair<String, Integer>> it -> it[0] } as Function
def list = new ArrayList<String>()
function.apply(list)
}
@Test
void functionWithPair1Test() {
// some function that operates on list and returns an element of this list
Function<List<Pair>, Pair> function =
{ List<Pair<String, Integer>> it -> it[0] } as Function
def list = new ArrayList<Pair>()
function.apply(list)
}
@Test
void functionWithPair2Test() {
// some function that operates on list and returns an element of this list
Function<List<Pair<String, Integer>>, Pair<String, Integer>> function =
{ List<Pair<String, Integer>> it -> it[0] } as Function
def list = new ArrayList<Pair<String,Integer>>()
function.apply(list)
}
}
函数functionWithoutPairTest
和functionWithPair1Test
编译成功,但functionWithPair2Test
失败并出现以下错误:
Error:(36, -1) Groovy-Eclipse: Groovy:[Static type checking] - Incompatible generic argument types. Cannot assign java.util.function.Function <java.util.List, org.apache.commons.lang3.tuple.Pair> to: java.util.function.Function <List, Pair>
Error:(38, -1) Groovy-Eclipse: Groovy:[Static type checking] - Cannot call java.util.function.Function <java.util.List, org.apache.commons.lang3.tuple.Pair>#apply(java.util.List <Pair>) with arguments [java.util.ArrayList <Pair>]
看起来 groovy 不喜欢嵌套泛型。就我而言,动态编译不是一个选项,严格的类型检查是一项硬性要求。
有没有人遇到类似的错误并有建议?