【发布时间】:2019-12-30 12:25:28
【问题描述】:
这是我正在尝试解决的当前问题,我们在 Kotlin 中有以下界面:
interface Parent<out Result, in Params> where Result : Any {
fun run(params: Params): Result
}
这里的问题是,有时我不想将任何参数传递给接口,所以我最终将 Unit 作为类型参数传递,而覆盖类最终看起来像这样:
class Child : Parent<String, Unit> {
override fun run(params: Unit): String { ... }
}
最终目标:当Params 是Unit 时,添加一些抽象以便“获取”一个完全没有参数的run 函数会很好
喜欢:
class Child : Parent<SomeEntity, Unit> {
override fun run(): Entity { ... }
}
或者更好的是,可以选择传递第二个类型参数,以便让一个类接受一个或两个类型参数。
class Child : Parent<String> {
override fun run(): Entity { ... }
}
与参数相同的父类
class Child : Parent<String, Int> {
override fun run(params: Int): String { ... }
}
这可能吗?
【问题讨论】:
-
我认为您在示例界面中更改了类型名称并且错过了更新它。 “实体”与“结果”或“参数”不匹配。
-
是的,我就是这么做的哈哈