Reputation: 11
The problem is when I try to get the reference to testVar
variable in Kotlin, ambiguity occurs if I have a function with the same name as the variable. Is there a solution for this?
class TestClassBuilder {
lateinit var mainVar: String
lateinit var testVar: String
fun mainVar(mainVar: String) = apply {
this.mainVar = mainVar
}
fun testVar(testVar: String) = apply {
this.testVar = testVar
}
fun build() {
if (!::testVar.isInitialized) {
testVar = mainVar.substring(0, 5)
}
// ...
}
}
I've tried to rename variable and, of course, it worked, but I'd like to know if there is a better solution.
Upvotes: 1
Views: 233
Reputation: 2108
You can't do anything with this problem, but you don't need it. If you use Kotlin properties it will generate setters for you.
First of all, please check how properties work - link
Then you use plain properties:
class TestClassBuilder {
lateinit var mainVar: String
lateinit var testVar: String
fun build() {
if (!::testVar.isInitialized) {
testVar = mainVar.substring(0, 5)
}
}
}
fun main() {
val builder = TestClassBuilder()
builder.mainVar = "some text"
}
And here is how you can use setters from Java:
public class C {
public static void main(String[] args) {
TestClassBuilder t = new TestClassBuilder();
t.mainVar = "some text"; // variant 1
t.setMainVar("another text"); // variant 2
}
}
Also you can add visibility modifiers for getters and setters or even custom logic:
var testVar: String = ""
set(value) {
field = if (value.startsWith("abc")) {
value.removePrefix("abc")
} else value
}
Upvotes: 0