我有功能的定义
abstract class AbstractDao<T>(private val dataStore: KotlinEntityDataStore<Persistable>): Dao<T> where T: Persistable
我需要从KClass
类型中获取T
。在Kotlin有可能吗?
由于type erasure,这是无法做到的。但是你可以提供一个reified type
的工厂方法,它委托给接受KClass
的构造函数。这是一个简化的例子:
class WithReifiedType<T> constructor(val kc: KClass<*>) {
companion object {
inline fun <reified T> getInstance(): WithReifiedType<T> {
println("Here's your KClass: ${T::class}")
return WithReifiedType(T::class)
}
}
}
//called like this
WithReifiedType.getInstance<String>()
创建顶级函数(作为伴随嵌入式工厂的替代方法)也可以接受,看起来像是调用者站点上的构造函数。
inline fun <reified T> WithReifiedType(): WithReifiedType<T> {
println("Here's your KClass: ${T::class}")
return WithReifiedType(T::class)
}
//called like this
WithReifiedType<String>()