如何在 Kotlin 中将类型传递给泛型方法? [英] How to pass a type to generic method in Kotlin?
问题描述
我有一个像下面这样的通用方法
I have a generic method like below
private fun <T> getSomething(): T {
return "something" as T
}
如何使用变量 T
类型调用此方法?
How can I call this method with a variable T
type?
val types = arrayListOf<Type>(String::class.java, Boolean::class.java)
types.forEach { type ->
val something = getSomething<type>() // Unresolved reference: type
}
在运行时,我不知道什么是泛型类型 T
.我从 types
获取类型,应该使用通用的 getSomething
方法传递它.
At runtime, I don't know what would be generic type T
. I am getting the type from types
and should pass it with generic getSomething
method.
我想调用有几个表的数据库.示例模型是这样的
I want to call database which has several table. Example models are like this
class User{
}
class Student{
}
由于所有的调用查询基本相同,我想有一个通用的方法来调用数据库和获取数据.
Since all the calling queries are basically same, I want to have generic method for calling database and get data.
private fun <T> getData(model: String): List<T>?{
return when(model){
"user" -> getUsers()
"student" -> getStudents()
else -> null
}
}
所以当我调用上面的方法时.在我的循环中,我想将 Type
作为 User
或 Student
传递.
So when I call above method. Within my loop I want to pass Type
as either User
or Student
.
val types = arrayListOf<Type>(User::class.java, Student::class.java)
types.forEach { type ->
val data = getData<type>(type.javaClass.simpleName) // Unresolved reference: type in <type>
}
我怎样才能实现它.
推荐答案
这是一个完整的例子:
import kotlin.reflect.KClass
data class User(val name: String)
data class Student(val name: String)
fun getUsers(): List<User> = listOf(User("JB"))
fun getStudents(): List<Student> = listOf(Student("Claire"))
fun <T: Any> getData(clazz: KClass<T>): List<T>? {
return when(clazz) {
User::class -> getUsers() as List<T>
Student::class -> getStudents() as List<T>
else -> null
}
}
fun main(args: Array<String>) {
val types = listOf(User::class, Student::class)
types.forEach { type ->
val data = getData(type)
println(data)
}
}
这篇关于如何在 Kotlin 中将类型传递给泛型方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!