Kotlin is great, Java is great, but there are sometimes little things that can be a little bit tricky. Especially when combining the two.
I am going to talk about one tricky thing now.
So we have an interface in Java:
And I wish to implement it using an enum in Kotlin.
Like so:
Obviously this will break, because a public val description automatically gets a getter in Kotlin, which conflicts with the implementation of the getDescription method.
You'll get error messages during compile time like this:
Platform declaration clash: The following declarations have the same JVM signature (getDescription()Ljava/lang/String;):
Well, you think, that's fine. If Kotlin already makes a getDescription automatically, I can simply remove my method getDescription() from the enum.
But that doesn't work. It immediately starts complaining that you have not implemented all members of the interface.
The way to solve it is to make the description field private ("private val description: String") so Kotlin no longer automatically creates a getter.
Trivial but a bit surprising.
From what I can tell, Kotlin is being careful not to create what they call "accidental overrides".
References
- YouTrack - KT-6653 - Kotlin properties do not override Java-style getters and setters (created 10 years ago)
- https://youtrack.jetbrains.com/issue/KT-6653
- YouTrack - KT-19444 - Add JVM-specific annotation to permit "accidental" overrides of interface members
- https://youtrack.jetbrains.com/issue/KT-19444
No comments:
Post a Comment