如何在Kotlin中将类型传递给泛型方法? [英] How to pass a type to generic method in Kotlin?

查看:1152
本文介绍了如何在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传递为UserStudent.

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

我如何实现它.

推荐答案

下面是一个完整的示例:

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中将类型传递给泛型方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆