【问题标题】:Kotlin : Casting an object to Generic classKotlin:将对象转换为通用类
【发布时间】:2019-08-04 03:02:46
【问题描述】:

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

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

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】:

    在实现泛型时,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&lt;T&gt; 参数添加到函数并使用 Class#cast 转换为 T

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

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

    【讨论】:

      猜你喜欢
      • 2021-12-17
      • 2019-02-19
      • 2021-07-03
      • 2021-01-23
      • 2017-10-15
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多