generics - Kotlin 通用工厂动态转换

标签 generics kotlin casting factory

我想创建具有通用参数的对象工厂:

interface Foo<T> {
    fun buzz(param: T)
}

我有两个测试实现:
class FooImpl1 : Foo<String> {
    override fun buzz(param: String) {
        // implementation 1
    }
}

class FooImpl2 : Foo<Int> {
    override fun buzz(param: Int) {
        // implementation 2
    }
}

现在我创建了 map 来包含我所有的实现
val implementationMap = mapOf<String, Foo<*>>(
    Pair(firstKey, FooImpl1()),
    Pair(secKey, FooImpl2())
)

我也有带参数的 map :
val paramMap = mapOf<String, Any>(
    Pair(firstKey, "String param"),
    Pair(secKey, 12)
)

但是现在当我从我的 map 中获取第一个元素时:
implementationMap.getValue(firstKey).buzz(paramMap.getValue(firstKey))

我的 buzz方法拒绝任何参数(希望 Nothing 作为类型)

所以我创建了另一个类型的 map
val classMap = mapOf<String, KClass<*>>(
    Pair(firstKey, FooImpl1::class),
    Pair(secKey, FooImpl2::class)
)

val paramClassMap = mapOf<String, KClass<*>>(
    Pair(firstKey, String::class),
    Pair(secKey, Int::class)
)

但我不能这样投:
implementationMap.getValue(firstKey)
    .cast < classMap.getValue(firstKey) > () // not possible
    .buzz(
        paramMap.getValue(firstKey)
        .cast < paramClassMap.getValue(firstKey) > () // not possible
    )

或者那个
(implementationMap.getValue(firstKey) // FooImpl1
    /*not possible */ as classMap.getValue(firstKey)) // (FooImpl1::class)
    .buzz(
        paramMap.getValue(firstKey) // String
        /*not possible */ as paramClassMap.getValue(firstKey)) // (String::class)

我也尝试使用 Token输入,但它无济于事:
val classMap = mapOf<String, Type>(
    Pair(firstKey, object: TypeToken<FooImpl1>() {}.type),
    Pair(secKey, object: TypeToken<FooImpl1>() {}.type)
)

任何想法如何正确地转换它?还是一些“不同的方法”的想法?

最佳答案

恐怕你只需要做一些未经检查的类型转换。

interface Foo<T> {
    fun buzz(param: T)
}

class FooImpl1 : Foo<String> {
    override fun buzz(param: String) {
        println(param)
    }
}

class FooImpl2 : Foo<Int> {
    override fun buzz(param: Int) {
        println(param)
    }
}

val implementationMap = mapOf<String, Foo<*>>(
        Pair("firstKey", FooImpl1()),
        Pair("secKey", FooImpl2())
)

val paramMap = mapOf<String, Any>(
        Pair("firstKey", "String param"),
        Pair("secKey", 12)
)


fun main() {
    @Suppress("UNCHECKED_CAST")
    val imp = implementationMap["firstKey"] as Foo<Any?>
    val param = paramMap["firstKey"]
    imp.buzz(param)
}

关于generics - Kotlin 通用工厂动态转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55606111/

相关文章:

c# - 在反序列化期间委托(delegate)调用泛型类内部的泛型方法挂住 CPU

android - 当我按下返回按钮时如何保存数据

java - 将对象转换为泛型(或将内部类变量存储为泛型)

java - 在Java中开发泛型修饰符的正确方法

swift - 检查泛型类型是否属于类内的特定类型

java - 更改泛型的空数组时出现意外的空指针异常

android - 我什么时候需要在 Gradle 依赖项中使用 Kapt?

kotlin - 如何在KDoc中引用辅助构造函数?

c - gdb:是否可以根据调试符号中不存在的用户定义结构来转换/重新解释序列

swift - 需要澄清 Swift 中的类型转换运算符