繁体   English   中英

Kotlin接口java类:意外覆盖

[英]Kotlin interface a java class: Accidental override

我有一个类似的第三方java库

public class ThirdParty  {
    public String getX() {
        return null;
    }
}

我在kotlin中也有一个界面

interface XProvider {
    val x: String?
}

现在我想扩展ThirdParty类并实现XProvider接口。 这在我的遗留Java代码中运行良好:

public class JavaChild extends ThirdParty implements XProvider {}

但是,我想写尽可能多的kotlin并尝试将我的java类转换为kotlin。 可悲的是,以下不起作用:

class KotlinChild: ThirdParty(), XProvider

错误是

class 'KotlinChild1' must be declared abstract or implement abstract member public abstract val x: String? defined in XProvider

但是,如果我做的话

class KotlinChild1: ThirdParty(), XProvider {
    override val x: String? = null
}

我明白了

error: accidental override: The following declarations have the same JVM signature (getX()Ljava/lang/String;)
    fun <get-x>(): String?
    fun getX(): String!
        override val x: String? = null

有效的是以下丑陋的解决方法:

class KotlinChild: JavaChild()

XProvider接口和ThirdParty(抽象)类之间存在命名冲突。 这是我编译的Kotlin编译器造成的

val x: String?

因为Java不支持变量或属性的继承,所以进入有效的Java方法。 有效的Java方法将具有名称“getX()”。 因此,XProvider.getX()和ThirdParty.getX()方法之间存在冲突。 所以解决方案可能是在XProvider类中重命名属性“x”。 或者,您创建第二个类,其中包含ThridParty的实例并实现XProvider。 当调用val x:String时,您可以通过从ThirdParty实例获取内容来提供内容。

例:

class ThirdPartyImpl: XProvider {
    private val thridPartyInstance = ThridParty()
    override val x: String? = thirdPartyInstance.x
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM