Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloning a Builder object in Kotlin

Tags:

java

kotlin

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?

like image 807
daniyelp Avatar asked Feb 02 '26 03:02

daniyelp


2 Answers

Make baseBuilder a function, not a value.

fun baseBuilder() = Builder("xx").setA("aa").setB("bb")

fun f(action: Action): Builder) {
  return baseBuilder().add(action)
}
like image 174
Louis Wasserman Avatar answered Feb 03 '26 17:02

Louis Wasserman


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
}
like image 25
Andreas Avatar answered Feb 03 '26 15:02

Andreas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!