Kotlin:将对象转换为Generic类

问题描述 投票:2回答:1

如何获取Generic类的类型并将对象强制转换为它?

我想使用此函数来传递Interface类:

protected fun <T> getInteraction(): T {
        return when {
            context is T -> context
            parentFragment is T -> parentFragment as T
            else -> throw IllegalArgumentException("not implemented interaction")
        }
    }

并使用它像:

 private var interaction: ISigninInteraction? = null

 override fun onAttach(context: Context?) {
        super.onAttach(context)
        interaction = getInteraction<ISigninInteraction>()

 }
android generics kotlin interface fragment
1个回答
2
投票

在实现泛型时,Kotlin,Java和JVM确实有类型擦除。泛型在字节码级别不可见。这意味着,您不能使用类型参数,例如T,直接在功能代码中。

Kotlin增加了对reified仿制药的支持,这对此有所帮助。你可以声明这个函数

inline fun <reified T> getIt() : T {
  ...
}

reifiedinline的帮助下,可以投射到T并将其归还。 https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters

第二种方法是遵循Java实践 - 将Class<T>参数添加到函数中,并使用Class#cast转换为T

您可以将reified inline函数与以下方法结合使用:

inline fun <reified T> getIt() = getIt(T::class.java)
© www.soinside.com 2019 - 2024. All rights reserved.