Jesse Gottlieb
02/04/2025, 8:12 PMapplyIf
, 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:
inline fun <T> T.applyIf(predicate: Boolean, f: T.() -> Unit) = apply {
if (predicate) f()
}
val myPlanBuilder = MyPlan.newBuilder()
myObjectBuilder.applyIf(isSunnyOutside) {
addPlanLineItem(goGetIceCream)
}
hfhbd
02/04/2025, 11:55 PMephemient
02/05/2025, 2:02 AMJesse Gottlieb
02/05/2025, 1:55 PM