首页 > 解决方案 > 如何在 kotlin 中为视频游戏实现 getComponent(/*Class*/) 方法

问题描述

我正在用 kotlin 编写,为 Android 开发基于文本的 RPG 游戏。我目前正在开发带有策略/实体组件设计的对象系统。我被困在 getComponent 函数上,不知道我在做什么

我需要一个方法来接受对 Class 类型的引用,然后将其与所有组件实例的类类型进行比较。

我尝试过使用泛型、KClass、Java 类型,但找不到答案。

我的主要问题是“as”运算符。我不知道它接受什么。

到目前为止我得到的是:

fun getComponent(clazz : KClass<*>) : Component? {
    for(component in components) {
        if(component is clazz) {
            return component
        }
    }
    return null
}

这段代码是错误的。IntelliJ 提醒我 clazz 不存在,因为它不是一个实际的类。

标签: kotlin

解决方案


您有一个KClass实例,它是一个表示类型的运行时对象,用于反射。您在这里有两个主要选择。您可以像这样使用reified generics,这样您就可以完全避免使用反射:

inline fun <reified T : Component> getComponent() : T? {
    for(component in components) {
        if(component is T) {
            return component
        }
    }
    return null
}

可以像这样调用此方法:

getComponent<SomeClass>()

或者,您可以使用KClass.isInstance

fun getComponent(clazz : KClass<*>) : Component? {
    for(component in components) {
        if(clazz.isInstance(component)) {
            return component
        }
    }
    return null
}

您也可以使用泛型和强制转换使这更方便一些:

fun <T : Component> getComponent(clazz : KClass<*>) : T? {
    for(component in components) {
        if(clazz.isInstance(component)) {
            return component as T
        }
    }
    return null
}

对于这两者,用法是相同的:

getComponent(SomeClass::class)

推荐阅读