Simplifying conditional modification with extension functions.
April 24, 2022
While using Jetpack Compose, you may have run into an instance where you needed to add a modifier only if a certain condition was true. You may have used a solution similar to this one:
Modifier.then(if (clickable) Modifier.clickable(onClick)else Modifier,)
This is certainly a valid way of adding a modifier conditionally, but it’s not particularly concise. To make the task at hand easier, you can instead create a helper modifier for conditional modification, which is possible because modifiers are declared as extension functions.
inline fun Modifier.thenIf(condition: Boolean,crossinline other: Modifier.() -> Modifier,) = if (condition) other() else this
This modifier can be used as follows:
Modifier.thenIf(clickable) { clickable(onClick) }
If you need to add multiple modifiers, remember to chain them:
Modifier.thenIf(clickable) {clickable(onClick).color(Color.Blue)}
Besides adding a modifier under a certain condition, you may need to add a modifier if a value is not null. In such a case, you’ll typically also want to use the not-null value in the modifier. In order to avoid using not-null assertion, you can once again create a helper modifier:
inline fun <T> Modifier.thenIfNotNull(value: T?,crossinline other: Modifier.(T) -> Modifier,) = if (value != null) other(value) else this
This modifier can be used as follows:
Modifier.thenIfNotNull(onClick) { clickable(it) }
© 2018–2023 Patrick Michalik