Kotlin从泛型类生成实例时提供类型

时间:2019-01-23 06:40:56

标签: generics kotlin

我可以通过下面的示例制作许多通用类

val company = Fragment<Company>
val location= Fragment<Location>
val employee = Fragment<Employee>

为了简化代码,我决定将所有类放入列表并在for循环中为每个类生成类

data class FragmentType(val entityClass: KClass<*>)
private val fragmentList: List<FragmentType> = listOf(
    FragmentType(Company::class),
    FragmentType(Location::class),
    FragmentType(Employee::class)
)

for(f in fragmentList){
    val fragment = Fragment<f.entityClass> //This is wrong
}

我知道for循环中的行是错误的,如何使用变量确定要生成的泛型类型?

2 个答案:

答案 0 :(得分:0)

在这种情况下,您可以使用enum

enum class FragmentType {
    COMPANY, LOCATION, EMPLOYEE
}

for(f in FragmentType.values()) {
    val fragment = when (f) {
        FragmentType.COMPANY -> Fragment<Company>
        FragmentType.LOCATION -> Fragment<Location>
        FragmentType.EMPLOYEE -> Fragment<Employee>
    }
}

答案 1 :(得分:0)

枚举(上面的答案)不是必需的。

val fragment = when(f.entityClass) {
    is Company -> Fragment<Company>
    is Location -> Fragment<Location>
    is Employee -> Fragment<Employee>
    else -> throw IllegalArgumentException("doesn't support class ${f.entityClass}")
}