Kotlin:麻烦理解泛型
我有一个模型实现两个接口
interface A interface B class Model() : A, B
当我传递一个参数作为我的Model类的List时,编译器知道Model是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 { }
我需要改变什么才能使其工作?
T
和Model
可能不是相同的类型。 因此,每个列表参数需要单独的通用参数:
fun <T1, T2> twoParamFunc(oldList: List<T1>, newList: List<T2>) where T1 : A, T1 : B, T2 : A, T2 : B { }