android - 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>()
}
解决方案
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)
推荐阅读
- python - Multiprocess.pool.map() 引发 ValueError:没有要连接的对象
- php - How to get the checkbox value in php html
- algorithm - Packrat 缓存:从右到左与从左到右?
- c# - 从 Outlook 拖放到 Winforms
- android - android-apt plugin is incompatible with the Android Gradle plugin. Please use 'annotationProcessor' configuration instead. Affected Modules:
- c# - Xamarin Forms 在 sqlite 数据库中保存图像
- r - 为什么使用 fread 函数在 R 中导入数据会导致特殊的数据类型比较错误,从而导致进一步的过滤问题
- java - spring mvc migrates to spring boot in spring mvc beans in xml and configruations also how to remove module dependancies?
- javascript - How to close dropdown when click anywhere in vue js
- react-native - 我在反应本机应用程序中使用 redux 来获取和显示数据,但它没有更新来自后端的数据更改