Having a bit of a headache with trying to mix Inte...
# getting-started
c
Having a bit of a headache with trying to mix Interfaces, Java Records, and Kotlin Data Classes. Given an interface definition of
Copy code
public interface JavaInterface {
    String aField();
}
We can create a record that implements it:
Copy code
public record JavaImplementation(String aField) implements JavaInterface {}
In the interface I named the method
aField()
to match the method generated by the record. As long as we're just in Java it's fine but it seems really awkward to have a Kotlin data class interface with it. The best I've come up with is:
Copy code
data class KotlinImplementation(
    val aField: String
) : JavaInterface {
    override fun aField() = aField
}
(The problem exists the other way round too. If my interface is in Kotlin with
aField
as the property then data classes become simple but records don't play nice because the Kotlin interface demands they implement
getAField()
which the record doesn't generate) As far as I can tell the fundamental issue is the naming convention records use. Has anyone come across this before and what's the most elegant way to get them to play nice with each other? Also the interface itself must be in Java.
a
does using @JvmField or @JvmRecord help?
c
Not as far as I can tell 😞
a
oh well
you could try creating a specific Kotlin implementation of
JavaInterface
, purely for purposes of interoping nicely
Copy code
interface JavaInterfaceKt : JavaInterface {
    val aField: String
    fun aField(): String = aField
}
👆 1
c
Booo 😞
p
Well, that linked issue is for ‘javabean’ `getX`/`setX` methods. For…reasons, records don’t use javabeans, and instead use functions with the same name as the record property Per the documentation,
@JvmRecord
on a data class should emit a proper JVM record with the same syntax for access from Java: https://kotlinlang.org/docs/jvm-records.html#declare-records-in-kotlin
Though that may not cover your core problem of implementing the interface homer disappear
Disappointingly, the decompiled bytecode looks approximately correct, it’s just that the kotlin compiler thinks you need to manually override