I have a generic method like below

private fun <T> getSomething(): T {
    return "something" as 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方法传递它.

Use case

我想调用有几个表的数据库.示例模型如下

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
    }
}

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>
}

How can I achieve it.

推荐答案

Here's a complete example:

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相关问答推荐

在Kotlin中,有没有一种函数方法将一个列表(N个元素)映射到一个相邻元素之和列表(N—1个元素)?

使用另一个对象的列表创建对象

处理合成层次 struct 中的深层按钮以切换视图

Scala性状线性化等价于Kotlin

有没有一种简单的方法来识别物体?

Kotlin - 什么时候和什么时候不喜欢内联函数,为什么?

在 kotlin 中使具体化字段可选

Kotlin 可打包类抛出 ClassNotFoundException

Kotlin 有垃圾收集器吗?如果是这样,它基于哪种算法?

内联函数导致单元测试代码覆盖率报告出错

在 Kotlin 中,当枚举类实现接口时,如何解决继承的声明冲突?

如何用 kotlin 打包 List

kotlin:扩展方法和空接收器

如何捕获传递给模拟函数的参数并返回它?

Kotlin Native如何将字节数组转换为字符串?

Spring Boot:更改属性占位符符号

TypeConverter()在Android的TypeConverter错误中具有私有访问权限

如何启用spring security kotlin DSL?

导航架构组件 - 未生成 DestinationFragmentArgs

将 androidx.constraintlayout:constraintlayout lib 更新到 2.0.2 版本后出现崩溃 isRtl () null 引用