首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在不知道类型的情况下从泛型函数中调用函数?

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

Stack Overflow用户
提问于 2020-11-07 02:00:03
回答 1查看 61关注 0票数 1

有没有办法做到以下几点?

代码语言:javascript
复制
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())
}

目前,结果是:以下代码都不能用提供的参数调用...

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-09 16:52:56

你需要多个接收器才能工作(KEEP-87)。有了这些,你将能够正确地“找到”接收器。

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

代码语言:javascript
复制
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?
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64719513

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档