【发布时间】:2020-11-06 18:00:03
【问题描述】:
有没有办法做到以下几点?:
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())
}
目前,结果是:不能使用提供的参数调用以下任何一个...
【问题讨论】:
-
不可能像您描述的那样自动执行此操作。即使使用具体类型,您也必须使用 when 语句来检查类型并手动选择适当的函数。
-
谢谢。我是这么想的。你会看到一个可能的解决方法吗?使用完全不同的东西?我只是想在类本身之外实现一些方法。包括一些接口会起作用,但是我需要在类中实现接口,而不是在外面。你看有没有别的办法?还是只有 KEEP-87(类型类)才能做到这一点?
-
扩展功能是否符合您的需求?
-
他们会,如果我可以定义一个不依赖于接口的通用函数,但更像是“这个扩展函数是为那个类型定义的吗?” (因为你不能用接口标记类(你在上面的通用函数中需要它)并在扩展函数中实现该接口......)
-
Haskell 可以通过类型类做到这一点,但有趣的是,其他一些编译的强类型静态语言可以做到这一点。 Crystal 可以做到——不问任何问题,Nim 也可以做到——不问任何问题。可惜 Kotlin 不能以任何方式做到这一点......
标签: kotlin generics functional-programming