android - Kotlin : Casting an object to Generic class

标签 android generics kotlin interface fragment

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

我想用这个函数来传递一个接口(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>()

 }

最佳答案

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

Kotlin 添加了对 reified 的支持泛型,这在这里有帮助。您可以像这样声明函数

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

reified的帮助下和 inline可以转换为 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)

关于android - Kotlin : Casting an object to Generic class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55141835/

相关文章:

java - 捕获转换不是递归应用的?

java - 通用类的 MessageBodyReader/Writer

java - 获取高阶函数中函数参数的名称

android - 找出当前位置

android - ArrayAdapter 的 getPositionForSection 和 getSectionForPosition 以及 getSections 方法

android - android中的RelativeLayout layout_below问题

c# - 一种在开放委托(delegate)和封闭委托(delegate)之间执行转换的方法

android - 从移动应用程序进行错误报告/记录的最佳工具

Kotlin - 一种将可变列表公开为不可变列表的优雅方式

android - AppModule.provideViewModelFactories(AppModule.kt) 处的 NoClassDefFoundError