10

I have a Java class of the format:

class JavaClass {
    private String name;
    private Boolean x;

    public String getName() { return name; }
    public void setName(String name) { this.name = name }

    public Boolean isX() { return x; }
    public void setX(Boolean x) { this.x = x }
}

And I am overriding this class into a Data class in Kotlin, which is of the format:

data class KotlinClass(
    var nameNew: String? = null,
    var xNew: Boolean = false
): JavaClass() {

    init {
        name = nameNew
        x = xNew
    }
}

When I do this, the name initialization this way doesn't give a problem, but I can't initialize x in this way. The IDE complains that x is invisible. Why with x and not with name?

I created a new variable in the Kotlin class with the name x with a custom getter and setter and it complains about an accidental override for the setter (That is understandable.). This means that the the Java setter and getter is visible in the Data class. So why is the setter not being used for x in the init block, like it is doing for name?

NSaran
  • 561
  • 3
  • 19

1 Answers1

7

This is because of how Kotlin represents Java getters and setters as properties. If the getter signature is T isSomething() (and not T getSomething()), then the Kotlin property is named isSomething as well (not just something) . And in your case, the x = xNew resolves to the private field access.

You can fix your code by assigning isX instead:

init {
    name = nameNew
    isX = xNew
}

Or, if you rename isX() to getX() in your Java code, then your x = xNew assignment will work.

hotkey
  • 140,743
  • 39
  • 371
  • 326
  • 1
    Thank you! A follow up question on this: `var isX: Boolean get() = isX() set(value) = setX(value)` You said that the isX will be a generated property. So will its signature look something like this? – NSaran Aug 08 '17 at 18:17
  • 1
    @user8138184, this is only a representation. It behaves *as if* there's a property implemented as you supposed, but it is not compiled to a real property (the Kotlin compiler just maps the reads and writes of this representation to real getter and setter calls). – hotkey Aug 08 '17 at 18:46