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?
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With