作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个实现两个接口(interface)的模型
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 { }
关于generics - Kotlin:难以理解泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37817018/
我想模拟这个函数: function getMetaData(key) { var deferred = $q.defer(); var s3 = vm.ini
我是一名优秀的程序员,十分优秀!