Kotlin - 如何按元素类型查找和转换元素

dan*_*iol 1 kotlin

我有一个继承的对象集合,Component我想要一个函数,它通过它的具体类找到一个对象并返回它。
但是 Kotlin 不喜欢我做的演员表,而且添加@Suppress("UNCHECKED_CAST")是丑陋的。

我有以下代码:

open class GameObjectImpl : GameObject {
    private val attachedComponents = mutableSetOf<Component>()

    @Suppress("UNCHECKED_CAST")
    override fun <TComponent : Component> getComponent(type: KClass<TComponent>): TComponent? {
         return attachedComponents.find { type.isInstance(it) } as? TComponent
    }
}
Run Code Online (Sandbox Code Playgroud)

ean*_*533 8

这应该适合你:

open class GameObjectImpl : GameObject {
    val attachedComponents = mutableSetOf<Component>()

    override inline fun <reified TComponent : Component> getComponent(type: KClass<TComponent>): TComponent? {
         return attachedComponents.filterIsInstance<TComponent>().firstOrNull()
    }
}
Run Code Online (Sandbox Code Playgroud)