gpt4 book ai didi

generics - Kotlin:难以理解泛型

转载 作者:行者123 更新时间:2023-12-03 06:42:17 24 4
gpt4 key购买 nike

我有一个实现两个接口(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 { }

我需要更改什么才能使其正常工作?

最佳答案

TModel 可能不是相同的类型。因此,您将需要为每个列表参数提供单独的通用参数:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com