Generics Kotlin:理解泛型有困难
我有一个实现两个接口的模型Generics Kotlin:理解泛型有困难,generics,kotlin,Generics,Kotlin,我有一个实现两个接口的模型 interface A interface B class Model() : A, B 当我将一个参数作为模型类的列表传递时,编译器理解模型是a和B。但当我传递两个参数时,其中一个参数的类型是T(其中T:a,T:B),编译器无法理解它 protected fun <T> test(givenList: List<T>) where T : A, T : B { val testList = ArrayList<Model&g
interface A
interface B
class Model() : A, B
当我将一个参数作为模型类的列表传递时,编译器理解模型是a和B。但当我传递两个参数时,其中一个参数的类型是T(其中T:a,T:B),编译器无法理解它
protected fun <T> test(givenList: List<T>) where T : A, T : B {
val testList = ArrayList<Model>()
oneParamFunc(testList) // will compile
oneParamFunc(givenList) // will compile
twoParamFunc(givenList, testList) // won't compile (inferred type Any is not a subtype of A)
twoParamFunc<T>(givenList, testList) // won't compile (Required List<T>, Found ArrayList<Model>)
}
protected fun <T> oneParamFunc(list: List<T>) where T : A, T : B { }
protected fun <T> twoParamFunc(oldList: List<T>, newList: List<T>) where T : A, T : B { }
protectedfun测试(givenList:List),其中T:A,T:B{
val testList=ArrayList()
oneParamFunc(testList)//将编译
oneParamFunc(givenList)//将编译
twoParamFunc(givenList,testList)//不会编译(推断的类型Any不是a的子类型)
twoParamFunc(givenList,testList)//不会编译(必需的列表,找到的ArrayList)
}
受保护的fun-oneParamFunc(list:list),其中T:A,T:B{}
受保护的参数func(oldList:List,newList:List),其中T:A,T:B{}
我需要更改什么才能使其工作?
T
和型号
可能不是相同的类型。因此,每个列表参数都需要单独的通用参数:
fun <T1, T2> twoParamFunc(oldList: List<T1>, newList: List<T2>)
where T1 : A, T1 : B, T2 : A, T2 : B { }
fun-twoParamFunc(旧列表:列表,新列表:列表)
其中T1:A,T1:B,T2:A,T2:B{}