i have a Builder class with a bunch of functions f...
# announcements
l
i have a Builder class with a bunch of functions for various types
.with(key: String, value: String)
,
.with(key: String, value: Boolean)
. i'd like to be able to call these functions conditionally on the call site. i can't think of anything better than simply adding a param
.with(key: String, value: String, shouldUse: Boolean)
to determine if a value should be used internally by the builder if
shouldUse
is true
n
Instead of just using a builder, have a function that accepts a lambda with the builder as receiver
Then they can just use if statements in the lambda
Assuming I understand correctly
Might help if you provide some toy code
l
Thanks! basically i have this: maybe it does make sense to accept a Predicate as lambda for each function? Having a hard code coding it
Copy code
class Event(val eventName: String) {
    val properties = mutableMapOf<String, Any>()

    fun with(key: String, value: Boolean): Event {
        properties[key] = value
        return this
    }
    fun with(key: String, value: Int): Event {
        properties[key] = value
        return this
    }
    fun with(key: String, value: Float): Event {
        properties[key] = value
        return this
    }
    fun with(key: String, value: String): Event {
        properties[key] = value
        return this
    }
}
n
Usually with builders the methods are named for properties they are setting
If you can't do that, then this doesnt really give you much that I can see over just using mutableMapOf directly, I guess it just restricts the type of the value to string, float etc
So you could do e.g.
Copy code
val builtEvent = Event("name").apply {
    with("foo", 5)
    if (condition) with("bar", 1.0)
}
Etc
I wouldn't call that method with since that's a bit confusing with the scope function