gpt4 book ai didi

generics - 从泛型函数返回特定实例

转载 作者:行者123 更新时间:2023-12-02 12:49:29 25 4
gpt4 key购买 nike

我的问题是关于泛型方法的类型推断。

我有以下情况:

interface Obj {
val Id: String
}
data class User(override val Id: String, val name: String): Obj
data class Case(override val Id: String, val subject: String): Obj

interface Api {
fun <T: Obj> getLastUpdated(type: KClass<T>, backTill: Duration = Duration.ofDays(1)): LastUpdated

fun <T: Obj> getDetails(type: KClass<T>, uuid: String): Details<T>

data class LastUpdatedResponse(val ids: List<String> = emptyList(),
val latestDateCovered: String = "")
data class LastUpdated(val error: Throwable? = null, val response: LastUpdatedResponse? = null)

data class DetailsResponse<T>(val wrapped: T)
data class Details<T>(val error: Throwable? = null, val response: DetailsResponse<T>? = null)
}

在我的测试中,我需要确切知道模拟 API 需要返回什么,因此
val testCase = Case("123", "Testing")
val testUser = User("321", "Dummy")
val mockApi = object: Api {
override fun <T : Obj> getLastUpdated(type: KClass<T>, backTill: Duration): Api.LastUpdated {
return Api.LastUpdated(response = Api.LastUpdatedResponse(listOf("123")))
}

override fun <T : Obj> getDetails(type: KClass<T>, uuid: String): Details<T> {
when (type) {
Case::class -> return Api.Details(response = Api.DetailsResponse(wrapped = testCase)) // <- this fails
User::class -> return Api.Details(response = Api.DetailsResponse(wrapped = testUser)) // <- as does this
else -> return Api.Details(error = UnsupportedOperationException())
}
}
}

但是,这无法编译:
Error:(114, 43) Kotlin: Type inference failed. Expected type mismatch: inferred type is Api.Details<Case> but Api.Details<T> was expected

我可以使它与类型转换一起工作:
when (type) {
Case::class -> return Api.Details(response = Api.DetailsResponse(wrapped = testCase)) as Api.Details<T>
User::class -> return Api.Details(response = Api.DetailsResponse(wrapped = testUser)) as Api.Details<T>

但是随后我收到一条警告,通知我“这个 Actor 永远不会成功” - 运行我的测试,它可以按预期工作。

我的问题是-为什么不进行强制转换就不能工作,我应该改用什么?

最佳答案

方差注释可能会对您有所帮助,只需更改通用参数 电话 输出对象 在以下函数中(在接口(interface)和实现类中):

fun <T: Obj> getDetails(type: KClass<T>, uuid: String): Details<out Obj>

关于generics - 从泛型函数返回特定实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37727319/

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