Idiomatic way how to implement Java interface properties in kotlin?

I didn’t find any detailed information about the rules how public getters of kotlin properties interoperate with inherited java methods.

For instance, I have Java interface:

public interface JavaNamed {

    String getName();

}

I want to implement it in Kotlin using simple property. What is the easiest and most idiomatic way to do it?

This does not work:

class KotlinNamed(override val name: String): JavaNamed

Surprise, name overrides nothing.

This does not work either:

class KotlinNamed(val name: String): JavaNamed {

    override fun getName() = name
    
}

looks promising, but in some later phase of the compilation, JVM name clash is detected.

Platform declaration clash: The following declarations have the same JVM signature (getName()Ljava/lang/String;):
fun <get-name>(): String defined in KotlinNamed
fun getName(): String defined in KotlinNamed

So the idiomatic way is this? Can’t we do better?

class KotlinNamed(private val _name: String): JavaNamed {

    override fun getName() = _name

}

Try your second example, but annotate val name: String with @JvmField. @JvmField val name: String I think that should work, since apparently that annotation stops Kotlin from automatically generating getters and setters.

Thanks, that works indeed.

But there is a simpler solution that I missed :man_facepalming: - simply declare the property private, which also suppresses the generated getter. So as easy as

class KotlinNamed(private val name: String): JavaNamed {

    override fun getName() = name
    
}
1 Like

Tbf, since the getters and setters are syntactic sugar, I think you should be able to use override val to implement that interface.