简体   繁体   English

Kotlin接口java类:意外覆盖

[英]Kotlin interface a java class: Accidental override

I have a third party java library with a class like 我有一个类似的第三方java库

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

I also have an interface in kotlin like 我在kotlin中也有一个界面

interface XProvider {
    val x: String?
}

Now I want to extend the ThirdParty class and implement the XProvider interface. 现在我想扩展ThirdParty类并实现XProvider接口。 This has been working fine in my legacy java code: 这在我的遗留Java代码中运行良好:

public class JavaChild extends ThirdParty implements XProvider {}

However, I would like to write as much kotlin as possible and am trying to convert my java classes to kotlin. 但是,我想写尽可能多的kotlin并尝试将我的java类转换为kotlin。 Sadly, the following does not work: 可悲的是,以下不起作用:

class KotlinChild: ThirdParty(), XProvider

Error is 错误是

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

However, if I do something like 但是,如果我做的话

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

I get 我明白了

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

What works is the following ugly work-around: 有效的是以下丑陋的解决方法:

class KotlinChild: JavaChild()

You have a naming conflict between the XProvider interface and the ThirdParty (abstract) class. XProvider接口和ThirdParty(抽象)类之间存在命名冲突。 This is caused my the Kotlin compililer which compiles 这是我编译的Kotlin编译器造成的

val x: String?

into a valid Java method because Java does not support the inheritance of variables or properties. 因为Java不支持变量或属性的继承,所以进入有效的Java方法。 The valid Java method will have the name "getX()". 有效的Java方法将具有名称“getX()”。 So you have a conflict between the XProvider.getX() and the ThirdParty.getX() method. 因此,XProvider.getX()和ThirdParty.getX()方法之间存在冲突。 So the solution might be to rename your property "x" in your XProvider class. 所以解决方案可能是在XProvider类中重命名属性“x”。 Or you create a second class that contains an instance of ThridParty and implements XProvider. 或者,您创建第二个类,其中包含ThridParty的实例并实现XProvider。 When val x: String is called you can provide the content by getting it from your ThirdParty instance. 当调用val x:String时,您可以通过从ThirdParty实例获取内容来提供内容。

Example: 例:

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