如何在Kotlin中没有泛型接口的情况下继承实现中的泛型类型?

时间:2019-07-17 01:01:21

标签: generics inheritance kotlin

我正在编写此SDK,在其中我需要在可公开访问的界面中将功能定义为:

interface CommonEndPoint {
   fun doSomething(listener: IListener<CommonType>)
}

,然后在子项目中实现通用接口为:

interface SpecialEndpoint : CommonEndpoint {
  fun doSomething(listener: IListener<SpecialType>)
}

SpecialType扩展CommonType的地方。

我将反变型通用侦听器定义为:

interface IListener<in T> {
   receiveResult(result: T)
}

问题是:

  1. 我需要SDK用户使用SpecialType,而不是CommonType
  2. 我需要按原样覆盖方法名称

这是到目前为止我尝试过的事情:

  • 我已经尝试了泛型函数,但是它们都无法工作,因为它们需要指定类型。
  • 我无法使用@JvmName,因为这些方法是打开/覆盖的
  • 此刻,我使用带有受保护/内部构造函数的抽象类来定义需要定义和实现的方法

为什么不使用通用接口?这些接口不是通用的,因为类型仅在一个函数中使用,但是侦听器应该是通用的,因为它们在项目中的任何地方都将使用。另外,应该为具有Objective-C兼容性的iOS实现相同的实现,这意味着我必须在那里支持轻量级泛型,如果使接口具有泛型,则必须为iOS编写三遍代码。

2 个答案:

答案 0 :(得分:0)

我认为您需要协方差而不是协方差才能使用SpecialType。我认为kotlin页面非常有帮助。 https://kotlinlang.org/docs/reference/generics.html

答案 1 :(得分:0)

最后,我不得不以这种形式使用通用的通用接口:

interface CommonEndPoint<TYPE1 : CommonType> {
    fun doSomething(listener: IListener<TYPE1>)
}

像这样在专用端点中继承:

interface SpecialEndpoint : CommonEndpoint<SpecialType> {
    fun doSomething(listener: IListener<SpecialType>)
}

最适合Java / Kotlin代码。然后删除侦听器,并切换到iOS / Objective-C的闭包,后者将转换为块。

相关问题