gpt4 book ai didi

kotlin - 为什么Kotlin无法自动转换通用类型

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

如果您熟悉unity3d,我将尝试为unity组件实现类似的模式:

AddComponent<T>();
GetComponent<T>();
所以我在 Kotlin 制作了这个片段:
val map = mutableMapOf<Class<Any>,IComponent>()

fun <T : IComponent> addComponent(component : T){
map.put(component.javaClass,component)
}
fun <T : IComponent> getComponent(klazz : Class<T>): T {
return map.get(klazz)
}
首先,我必须将一个类传递给getComponent方法,我无法像C#那样从T推断类型,我想知道是否有办法做到这一点。
最重要的是,尽管我确实说过T是一个IComponent,但为什么该方法会给我一个编译错误,说我在需要T的地方返回IComponent呢?
我必须强制转换为不安全的T,这在C#Universe中可以正常工作,但是我对Kotlin并不陌生,我想知道是否有可能。

最佳答案

First of all, I have to pass a class to the getComponent method, I can't infer the type from T like C# and I was wondering if there is a way to do this


为了能够执行此类操作,类型必须为 reified
在您的情况下,将是这样的:
inline fun <reified T : IComponent> getComponent(): T {
val klazz = T::class.java
// something-something that returns T
}

and most importantly, why is the method giving me a compile error saying the I'm returning IComponent where T is required, although I did say that T IS an IComponent


您说的 T类型是 IComponent,但不是 IComponentT。并且 map包含 IComponent作为值。其中一些可以是 T,但不能保证编译器确实如此。因此,编译器会出错,并说不确定从 T中是否会得到 map类型的东西。
因此,您需要将 force cast结果转换为以下类型:
return map.get(klazz) as T // in your case you will have to cast klazz to Class<Any>, btw
为了使其成为城堡,您应该将 map定义为
val map = mutableMapOf<Class<*>,IComponent>()
代替
val map = mutableMapOf<Class<Any>,IComponent>()

同样,最好将可选类型 T?用于 getComponent,并与条件转换 as?结合使用。

关于kotlin - 为什么Kotlin无法自动转换通用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64373064/

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