I have the following Kotlin code, which is a simplification of my problem:
val baseBuilder : Builder =
Builder("xx")
.setA("aa")
.setB("bb")
fun f(action: Action): Builder {
var extraBuilder = baseBuilder
.add(action)
return extraBuilder
}
If I call f many times I end up with a builder having many actions added to it, but I want f to return a builder that has only one action. I can't change the implementation of that Builder class. I thought of making a copy of the baseBuilder inside the f function but I couldn't find how. Or maybe I can achieve what I want in other way?
Make baseBuilder a function, not a value.
fun baseBuilder() = Builder("xx").setA("aa").setB("bb")
fun f(action: Action): Builder) {
return baseBuilder().add(action)
}
The builder is simple setup, nothing heavy, so just change baseBuilder to be a method, so every call creates and new builder.
fun baseBuilder() : Builder {
return Builder("xx")
.setA("aa")
.setB("bb")
}
fun f(action: Action): Builder {
var extraBuilder = baseBuilder()
.add(action)
return extraBuilder
}
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