dealing with calling a java based fluent/builder a...
# getting-started
j
dealing with calling a java based fluent/builder api conditionally -- right now i've gotten to:
Copy code
return 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:
Copy code
return ....apply {
   if (booleanFlag) { withBoolean() }
}
which is a little cleaner but might not work with all builder impls?
a
Modifiers in Compose lend themselves to similar shapes; over there a utility like this ends up being useful:
Copy code
inline fun <T> T.buildIf(condition: Boolean, builder: T.() -> T) = if (condition) builder() else this
then you end up with this at the call site:
Copy code
Builder.builder()
  .withIntParam(intParam)
  .buildIf(booleanFlag) { withBoolean() }
  .build()
đź‘Ť 1
🆒 2
m
I’ve written this helpful little scope function which nicely encapsulates the if/else you need.
Copy code
/**
 * 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
Copy code
return Builder.builder()
  .withIntParam(intParam)
  .runIf(booleanFlag) { withBoolean() }
  .build()
e
j
Cool, any way to set up a contract (?) such that if
condition
is something like
param != null
then param is smart cast to non-nullable in the passed in lambda?