【问题标题】:Optional generic parameters in KotlinKotlin 中的可选泛型参数
【发布时间】: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 { ... }
}

最终目标:当ParamsUnit 时,添加一些抽象以便“获取”一个完全没有参数的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 { ... }
}

这可能吗?

【问题讨论】:

  • 我认为您在示例界面中更改了类型名称并且错过了更新它。 “实体”与“结果”或“参数”不匹配。
  • 是的,我就是这么做的哈哈

标签: generics kotlin


【解决方案1】:

我不认为你可以用一个界面做任何特别的事情。 ?‍♂️
想到的一种解决方案是创建一个具有单个类型参数的子接口,该接口覆盖 Unit 函数,该函数委托给另一个不带参数的函数。
比如:

interface Parent1<out Result> : Parent<Result, Unit> {
    override fun run(params: Unit): Result = run()
    fun run(): Result
}

【讨论】:

    【解决方案2】:

    您可以创建一个处理Parents 的扩展函数,其中第二种类型是单元。仅当第二种类型与 Unit 匹配时,该函数才可用:

    fun <Result> Parent<Result, Unit>.run() = run(Unit)
    

    您使用的术语不典型。实现接口的类不是该接口的子类。它是其超类的子类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多