dorche
04/07/2026, 2:54 PMfun Modifier.conditional(
condition: Boolean,
positive: Modifier.() -> Modifier,
negative: Modifier.() -> Modifier = { this }
): Modifier = if (condition) positive(this) else negative(this)
fun <T> Modifier.nullConditional(
value: T?,
positive: Modifier.(T) -> Modifier,
negative: Modifier.() -> Modifier = { this }
): Modifier = value?.let {
positive(this, value)
} ?: negative(this)sindrenm
04/07/2026, 2:58 PMthen?
Modifier
.size(500.dp)
.then(
if (condition) {
Modifier.background(Color.Green)
} else {
Modifier.background(Color.Red)
}
)
Or even extract it, if it's used often:
fun Modifier.redOrGreen(condition: Boolean): Modifier {
return if (condition) {
this.background(Color.Green)
} else {
this.background(Color.Red)
}
}
Modifier
.size(500.dp)
.then(Modifier.redOrGreen(condition)dorche
04/07/2026, 3:01 PMMichael Krussel
04/07/2026, 3:20 PMconditional function could be made inline to avoid any penalty.
But in general a nice named function give more context then generic functions like conditional. Not sure if the then approach is more readable at the call site. My guess is that they are both very similar.sindrenm
04/07/2026, 3:24 PMthen approach, myself. The penalty is negligible in either case, IMO. 👍David
04/07/2026, 4:03 PM@Composable
inline fun Modifier.applyIf(condition: Boolean, block: @Composable Modifier.() -> Modifier): Modifier =
if (condition) {
this.then(Modifier.block())
} else {
this
}David
04/07/2026, 4:05 PMModifier.then() with and if statementdorche
04/07/2026, 4:22 PMinline for now and review all our call-sites to make sure it's actually an improvement over pure then .David
04/07/2026, 4:41 PMdorche
04/07/2026, 4:50 PM.conditional example and .applyIf functions are not much different for example.Agung Watanabe
04/08/2026, 5:26 AMfun Modifier.thenIf(
predicate: Boolean,
ifTrue: Modifier.() -> Modifier,
): Modifier {
return when {
predicate -> then(ifTrue(Modifier))
else -> this
}
}
fun Modifier.thenIf(
predicate: Boolean,
ifTrue: Modifier.() -> Modifier,
ifFalse: Modifier.() -> Modifier,
): Modifier {
return then(
when {
predicate -> ifTrue(Modifier)
else -> ifFalse(Modifier)
}
)
}
fun <T : Any> Modifier.thenIfNotNull(
element: T?,
ifTrue: Modifier.(T) -> Modifier,
): Modifier {
return when {
element != null -> then(ifTrue(element))
else -> this
}
}
fun <T> Modifier.thenIfNotNull(
element: T?,
ifTrue: Modifier.(T) -> Modifier,
ifFalse: Modifier.() -> Modifier,
): Modifier {
return then(
when {
element != null -> ifTrue(element)
else -> ifFalse(Modifier)
}
)
}