我想创建一个通用函数,允许将上下文转换为传入参数的活动类型。
这个想法的例子:
private fun <T> castContext(activityType: T): T{
//example activityType = MainActivity
return context as T
}
为此,您需要提供类型信息,通常仅在编译时可用(由于类型擦除)。在Java中,你会提供的实例Class
或叫什么type token
。
1 如果类型信息在编译时可用,则可以使用
private inline fun <reified T: Any> castContext(activity: Any?): T {
return activity as T
}
内联函数是仅编译时构造,因此可以代替您将类型信息“嵌入”到字节码中(如将其作为函数参数显式传递)——这是通过对泛型类型参数进行具体化来完成的。
您可以将通用参数范围进一步缩小Any
到您希望针对您的需要专门化此功能的任何内容。
2 如果你想动态地转换到某个类的实例,在编译时未知,你需要做一个正常的转换:
val type: KClass<*> = ...
type.cast(instance)
type.safeCast(instance)
因为 Kotlin 的as
和as?
关键字不是方法(这让()
我很恼火,因为经常需要额外的转换,我正在使用这对函数:
/** @return this as instance of the specified type (equivalent to this as T) */
inline fun <reified T: Any> Any?.asIs(): T = this as T
/** @return this as instance of the specified type (equivalent to this as? T) */
inline fun <reified T: Any> Any?.asIf(): T? = this as? T
使用Any?
as 方法接收器有些争议,因为隐式处理 null,而不是在调用站点上显式处理,使用?.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句