Menu

1 / 4

Branching Without the Else: A Field Guide to Kotlin’s onTrue, onFalse and ifOrNull

DEV Community: kotlin·Android Expert·about 6 hours ago
#J8YonTEc
#devtokotlin#devto#dev#enter#exit
Reading 0:00
15s threshold

Every Android codebase has the same small shape repeated hundreds of times. You call something that returns a Boolean , you do one thing if it was true, maybe another if it was false, and then you carry on with the flag. It is never a big decision, but it is almost always four to six lines of braces around a one-line idea.

Kotlin 2.5.0-Beta2 introduces three experimental standard library functions aimed squarely at that shape: onTrue() , onFalse() and ifOrNull() . They are small, and small APIs deserve the most scrutiny, because they get used everywhere and misused quietly.

This post covers what the functions do, where they genuinely improve Android code, and the failure modes I would want a teammate to warn me about before I merge a pull request.

The three functions in one minute

fun Boolean . onTrue ( action : ( ) -> Unit ) : Boolean fun Boolean .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.