11

I have a third party java library with a class like

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

I also have an interface in kotlin like

interface XProvider {
    val x: String?
}

Now I want to extend the ThirdParty class and implement the XProvider interface. This has been working fine in my legacy java code:

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. 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()
dpoetzsch
  • 757
  • 1
  • 7
  • 19

1 Answers1

2

You have a naming conflict between the XProvider interface and the ThirdParty (abstract) class. This is caused my the Kotlin compililer which compiles

val x: String?

into a valid Java method because Java does not support the inheritance of variables or properties. The valid Java method will have the name "getX()". So you have a conflict between the XProvider.getX() and the ThirdParty.getX() method. So the solution might be to rename your property "x" in your XProvider class. Or you create a second class that contains an instance of ThridParty and implements XProvider. When val x: String is called you can provide the content by getting it from your ThirdParty instance.

Example:

class ThirdPartyImpl: XProvider {
    private val thridPartyInstance = ThridParty()
    override val x: String? = thirdPartyInstance.x
}
Jonas Franz
  • 555
  • 1
  • 8
  • 18
  • 1
    I understand the problem and see your workaround. I have a lot of sub classes of `ThirdParty` (in my case `ParseObject`) in java which I'm trying to convert to kotlin now and this is where the problem occurred. Your solution would not only mean to change a lot of code but would also change the external interface (`XProperty`) of my library. – dpoetzsch May 10 '17 at 14:04
  • What is about the second solution? – Jonas Franz May 10 '17 at 14:07
  • The wrapper approach would mean I'd have to wrap all public methods that I use in my project internally which in my opinion is pretty ugly as well. – dpoetzsch May 10 '17 at 14:07