如何在不知道类型的情况下从泛型函数调用函数?

时间:2020-11-06 18:00:03

标签: kotlin generics functional-programming

是否可以执行以下操作?


class Someotherthing
class SomeotherthingDTO

class Something
class SomethingDTO

fun convert(entity: Someotherthing): SomeotherthingDTO = SomeotherthingDTO()
fun convert(entity: Something): SomethingDTO = SomethingDTO()

fun <T, D> generic(entity: T): D {
    // TODO: check here if there is convert() that accepts type T?! somehow? reflection? reification? or it will be possible only in the future by using typeclasses (KEEP-87)?
    return convert(entity)
}

fun main() {
    val x: SomethingDTO = convert(Something())
    println(x.toString())
}

当前的结果是:使用提供的参数无法调用以下任何内容...

1 个答案:

答案 0 :(得分:0)

您需要多个接收器才能使其正常运行(KEEP-87)。有了这些,您就可以正确地“找到”接收器。

在此之前,我通常要做的是将Converter放在ConverterRegistry中以进行如下转换:

interface Converter<A, B> {
    val fromClass: KClass<A>
    val toClass: KClass<B>

    fun convert(from: A): B

    fun convertBack(from: B): A
}

interface ConverterRegistry {
    fun <A, B> tryConvert(from: KClass<A>, to: KClass<B>): B?
}