首页 > 解决方案 > Kotlin:将对象转换为通用类

问题描述

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

我想用这个函数来传递一个接口类:

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>()

 }

标签: androidgenericskotlininterfacefragment

解决方案


Kotlin, Java and JVM do have types erasure when Generics are implemented. Generics are not visible at the bytecode level. It means, you cannot use type parameters, e.g. T, directly in the function code.

Kotlin adds support for reified generics, which helps here. You may declare the function like

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

With the help of reified and inline it will be possible to cast to T and return it. https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters

The second alternative is to follow a Java practice - add the Class<T> parameter to the function and use Class#cast to cast to T instead.

You may combine the reified inline function with the approach like:

inline fun <reified T> getIt() = getIt(T::class.java)

推荐阅读