CodeToLive

Kotlin Control Flow

Understand conditionals and loops in Kotlin.

If Expression

// Traditional if
val max = if (a > b) a else b

// If-else if ladder
val grade = if (score >= 90) {
    "A"
} else if (score >= 80) {
    "B"
} else {
    "C"
}

When Expression

// Similar to switch in other languages
when (x) {
    1 -> print("x is 1")
    2 -> print("x is 2")
    else -> print("x is neither 1 nor 2")
}

// When with ranges
when (score) {
    in 90..100 -> "A"
    in 80..89 -> "B"
    else -> "C"
}

For Loops

// Range loop
for (i in 1..5) {
    println(i)  // 1, 2, 3, 4, 5
}

// Iterate over collection
val names = listOf("Alice", "Bob", "Charlie")
for (name in names) {
    println(name)
}

// With index
for ((index, name) in names.withIndex()) {
    println("$index: $name")
}

While Loops

// While loop
var i = 1
while (i <= 5) {
    println(i)
    i++
}

// Do-while loop
do {
    println(i)
    i--
} while (i > 0)

Break and Continue

// Break example
for (i in 1..10) {
    if (i > 5) break
    println(i)
}

// Continue example
for (i in 1..10) {
    if (i % 2 == 0) continue
    println(i)  // Prints odd numbers
}
← Back to Tutorials