Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Setting a private Boolean in Java class via a Data class in Kotlin. Why am I not able to do this?

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?

like image 841
NSaran Avatar asked Aug 08 '17 17:08

NSaran


People also ask

Can I use Kotlin data class in Java?

As a quick refresher, Kotlin is a modern, statically typed language that compiles down for use on the JVM. It's often used wherever you'd reach for Java, including Android apps and backend servers (using Java Spring or Kotlin's own Ktor).

Is Boolean a data type in Kotlin?

Android Dependency Injection using Dagger with Kotlin To handle such situation Kotlin has a Boolean data type, which can take the values either true or false.


1 Answers

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.

like image 168
hotkey Avatar answered Oct 17 '22 07:10

hotkey