Java Interop: Apply @JvmName to getters of properties in interface or abstract class

Viewed 3948

Usually, we can write the following code in kotlin:

val hasValue : Boolean
    @JvmName("hasValue") get() = true

This will generate the method hasValue() instead of getHasValue() for Java interop.

However, in an interface, this gives me a compile error:

val hasValue : Boolean
   @JvmName("hasValue") get

The same goes for the following declaration in an abstract class:

abstract val hasValue : Boolean
    @JvmName("hasValue") get

So here is my question: How can I tell the kotlin compiler to use hasValue() instead of getHasValue() for getters (and setters) of properties in a kotlin interfaces?

3 Answers

I turns out, this is possible:

interface Foo {
    val bar: String
        @get:JvmName("getAwesomeBar") get
}

However, it is interesting that this does NOT work:

interface Foo {
    @get:JvmName("getAwesomeBar") 
    val bar: String
}

But, this does work:

class Foo {
    val bar: String
        @JvmName("getAwesomeBar") get() = "My bar value"
}

and this works too!

class Foo {
    @get:JvmName("getAwesomeBar") 
    val bar: String
        get() = "My bar value"
}

Why you need to have the extra get: when doing this in interfaces is beyond me. I'm sure there is a reason for it.

Related