Generics 如何在实现中继承泛型类型而不在Kotlin中使用泛型接口?
我正在编写此SDK,其中我需要在可公开访问的接口中定义以下功能:Generics 如何在实现中继承泛型类型而不在Kotlin中使用泛型接口?,generics,inheritance,kotlin,Generics,Inheritance,Kotlin,我正在编写此SDK,其中我需要在可公开访问的接口中定义以下功能: interface CommonEndPoint { fun doSomething(listener: IListener<CommonType>) } 接口公共端点{ 有趣的事情(听众:IListener) } 然后在子项目中实现公共接口,如下所示: interface SpecialEndpoint : CommonEndpoint { fun doSomething(listener: IList
interface CommonEndPoint {
fun doSomething(listener: IListener<CommonType>)
}
接口公共端点{
有趣的事情(听众:IListener)
}
然后在子项目中实现公共接口,如下所示:
interface SpecialEndpoint : CommonEndpoint {
fun doSomething(listener: IListener<SpecialType>)
}
接口SpecialEndpoint:CommonEndpoint{
有趣的事情(听众:IListener)
}
其中SpecialType扩展了CommonType
我已将逆变通用侦听器定义为:
interface IListener<in T> {
receiveResult(result: T)
}
接口转换器{
接收结果(结果:T)
}
问题是:
- 我尝试过泛型函数,它们也不起作用,因为它们需要指定类型
- 我无法使用@JvmName,因为这些方法是打开/重写的
- 目前,我使用带有受保护/内部构造函数的抽象类来定义需要定义和实现的方法
为什么不是泛型接口?接口不是泛型的,因为类型只在一个函数中使用,但是监听器应该是泛型的,因为它们在项目中随处可见。另外,对于具有Objective-C兼容性的iOS,也应该执行相同的实现,这意味着我必须在那里支持轻量级泛型,如果我将接口设置为泛型,我必须为iOS编写三次代码。我认为要使用SpecialType,需要协方差而不是逆变。我认为kotlin页面非常有用 最后,我不得不以这种形式使用通用接口:
interface CommonEndPoint<TYPE1 : CommonType> {
fun doSomething(listener: IListener<TYPE1>)
}
接口公共端点{
有趣的事情(听众:IListener)
}
并在专门的端点中继承,如下所示:
interface SpecialEndpoint : CommonEndpoint<SpecialType> {
fun doSomething(listener: IListener<SpecialType>)
}
接口SpecialEndpoint:CommonEndpoint{
有趣的事情(听众:IListener)
}
这对于Java/Kotlin代码非常有效。放下监听器,切换到iOS/Objective-C的闭包,将其转换为块。实际上,我阅读了该文档,但它对本例没有帮助。问题是这些方法不能具有相同的签名。这里不能使用协变类型,因为它们是由“out”关键字指定的,这意味着它们可以是方法的输出(返回值),而侦听器类型是一个输入。因此,您对接口的要求与您希望对使用施加的限制相矛盾。你能详细说明一下需要的原因吗?