Member-only story
Kotlin Control Flow (Kotlin Tutorial #2)
2 min readNov 6, 2023
Control flow mechanisms guide the execution order of code snippets within a program.
Kotlin, much like other programming languages, provides constructs to manage how the code runs, allowing for conditional execution, looping, and branching.
We’ll look at some of the main control flow statements in Kotlin:
- if
- when
- for
- while
If Expression
In Kotlin, `if` is not just a statement but an expression, meaning it can return a value.
Here’s how you can use `if`:
fun main() {
val a = 2
val b = 3
val max = if (a > b) {
println("a is greater")
a // The value of a is returned from the 'if' expression
} else {
println("b is greater")
b // The value of b is returned from the 'else' expression
}
println("max = $max")
}
2. When Expression
Kotlin’s `when` acts as a more versatile replacement for the `switch` statement found in other languages.
Here’s a basic use case for `when`:
fun main() {
val x = 2
when (x) {
1 -> println("x == 1")
2 -> println("x == 2")
else -> {
println("x is neither…