Joe
04/29/2021, 5:11 PMreturn Builder.builder().withIntParam(intParam).let {
if (booleanFlag) {
it.withBoolean()
} else {
it
}
}.build()
anyone have a better pattern for something this? assuming the builder is mutable/side-effecty can change it to something like:
return ....apply {
if (booleanFlag) { withBoolean() }
}
which is a little cleaner but might not work with all builder impls?Adam Powell
04/29/2021, 5:16 PMinline fun <T> T.buildIf(condition: Boolean, builder: T.() -> T) = if (condition) builder() else this
then you end up with this at the call site:
Builder.builder()
.withIntParam(intParam)
.buildIf(booleanFlag) { withBoolean() }
.build()
Michael Böiers
04/30/2021, 5:19 AM/**
* returns the receiver if the condition doesn't hold, otherwise acts like a normal run
*/
public inline fun <T> T.runIf(condition: Boolean, block: T.() -> T): T = if (!condition) this else run(block)
with that you would just write
return Builder.builder()
.withIntParam(intParam)
.runIf(booleanFlag) { withBoolean() }
.build()
elizarov
04/30/2021, 2:10 PMJoe
04/30/2021, 4:19 PMcondition
is something like param != null
then param is smart cast to non-nullable in the passed in lambda?