Kotlin's Control Flow Expressions: `if` and `when`

In Kotlin, `if` and `when` are expressions that return a value. This lets you assign their result directly to a variable, replacing Java's ternary operator. The footgun: when used as an expression, you must have an `else` branch to cover all cases.
In Kotlin, control flow constructs like `if` and `when` are expressions that return a value, not just statements. This lets you assign their result directly to a variable, cleaning up code by removing temporary mutable variables. It's Kotlin's replacement for the ternary operator. Use it for assigning conditional values, like choosing a display string or a configuration setting. The footgun: when used as an expression, the compiler requires it to be exhaustive.
Read the original → kotlinlang.org
- #kotlin
- #android
- #control flow
- #expressions
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.