daniyelp
daniyelp

Reputation: 1265

Cloning a Builder object in 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?

Upvotes: 3

Views: 200

Answers (2)

Andreas
Andreas

Reputation: 159114

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
}

Upvotes: 4

Louis Wasserman
Louis Wasserman

Reputation: 198143

Make baseBuilder a function, not a value.

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

fun f(action: Action): Builder) {
  return baseBuilder().add(action)
}

Upvotes: 4

Related Questions