如何使用类类型及其派生类作为集合的通用键和值?

时间:2019-07-04 11:36:29

标签: generics kotlin collections

很抱歉,如果这里没有解决方案,找不到它。

我想使用地图/词典来保存组件列表。所有组件都从同一类继承。因此,为了使事情整洁,我想使用该类作为键,并且在正确的列表中仅包含该类的组件:

private val components : Map<KClass<T : IComponent>, List<T>>

示例代码:

class GameObject
{
    val components : ObjectMap<KClass<out IComponent>, Array<*>> = ObjectMap()

    fun update(deltaTime: Float)
    {
        for(componentFamily in components.values())
        {
            for(component in componentFamily)
            {
                component.update(deltaTime)
            }
        }
    }

    inline fun <reified T : IComponent> get() : T?
    {
        return components.get(T::class)[0] // This does not work - it returns Any?, not T?
    }
}

执行我的代码尝试执行的操作。我知道这是错误的,但希望您能明白。

键:从IComponent继承的类 值:相同类型的对象,例如它们所在的键。

感谢您的光临:)

0 个答案:

没有答案