Hey folks I had an idea for predicated scope funct...
# language-proposals
j
Hey folks I had an idea for predicated scope functions. Wondering if anyone has proposed these before or if they are a good candidate for a KEEP. The idea is to add
applyIf
,
applyUnless
,
alsoIf
, and
alsoUnless
to the standard lib. I chose
apply
and
also
among the various scope functions because these functions simply return the receiver object, so the return type can still be known regardless of the predicate. As a server developer, I use
applyIf
on builder objects quite frequently and my company has added it to an internal shared kotlin library. I suspect many kotlin devs use some version of this already. An example would be:
Copy code
inline fun <T> T.applyIf(predicate: Boolean, f: T.() -> Unit) = apply {
  if (predicate) f()
}

val myPlanBuilder = MyPlan.newBuilder()

myObjectBuilder.applyIf(isSunnyOutside) {
  addPlanLineItem(goGetIceCream)
}
h
This idea/feature request was requested multiple times in the past. Personally, I don’t see a advantage compared to a simple if: if is easier to read, easier to understand and easier to debug. I try to not overuse scope functions for these reasons. Don’t be afraid of if and additional variables.
5
👍 1
e
definitely not going to be in stdlib before https://youtrack.jetbrains.com/issue/KT-32993
👌 2
j
ok, understood!