The Setup:
Our kotlin codebase pulls in an external java api (we don’t have control over). This java api, exposes properties as public on java classes.
Below is the external java class
public class TestClass {
// notice these properties are public
public int value;
public boolean isSetValue;
public void setValue(int value) {
this.value = value;
this.isSetValue = true;
}
public int getValue() {
return this.value;
}
public boolean getIsSetValue() {
return this.isSetValue;
}
}
In Kotlin, we use the class
fun main(){
val t = TestClass().apply {
value = 1
}
// evaluates to false because the code above directly sets the public property and does not call the setter function
println(t.isSetValue)
}
The Problem:
There are two issues:
-
because the java value property is public , the value property gets directly set and the setter function is never called.
-
if we try to directly call the setter
TestClass().apply {
setValue(1)
}
intelliJ throws a warning at us, arguably this is a bug, because IntelliJ infers that setting property is the same as calling the setter functions (which is clearly not the case). This warning is causing us lot of pain and causing devs to update their syntax thinking the =
op setter in this case is the same as calling the setter function. This kinda nuanced syntax can be hard to spot in code reviews since its tough to know if the object we’re accessing in kotlin is java with public field vs java with private field or simply kotlin based
Use of setter method instead of property access syntax
Requested Solution:
- I believe the intelliJ warning is arguably a bug, it shouldn’t throw a warning and ask to use another operator if the outcome is not the same (i.e if we 're not calling the same code path and logic altogether especially that the warning suggestion is wrong). that’s just confusing devs and it is something we hit often with new devs and had caused failures.
We may be able to turn off the warning at a repo level but for the most part we did want to adhere to using=
op for setter when possible. - It would be nice if we can have a compile flag to direct kotlin to use the setter when java properties are public. In our case, we want to use the setter with
=
op setter syntax but due to an external library we’re unable to. A compiler flag will tremendously help us