https://kotlinlang.org logo
#getting-started
Title
# getting-started
j

Joe

04/29/2021, 5:11 PM
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

Adam Powell

04/29/2021, 5:16 PM
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

Michael Böiers

04/30/2021, 5:19 AM
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

elizarov

04/30/2021, 2:10 PM
j

Joe

04/30/2021, 4:19 PM
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?
2 Views