kotlin-loops-and-conditions.md

#Conditions and loops

Last modified: 05 August 2025

Kotlin gives you flexible tools to control your program's flow. Use if, when, and loops to define clear, expressive logic for your conditions.


#If expression

To use if in Kotlin, add the condition to check within parentheses () and the action to take if the result is true within curly braces {}. You can use else and else if for additional branches and checks.

You can also write if as an expression, which lets you assign its returned value directly to a variable. In this form, an else branch is required. The if expression serves the same purpose as the ternary operator (condition ? then : else) found in other languages.

For example:

kotlinvar taller = heightAlice
if (heightAlice < heightBob) taller = heightBob

// Uses an else branch
if (heightAlice > heightBob) {
    taller = heightAlice
} else {
    taller = heightBob
}

// Uses if as an expression
taller = if (heightAlice > heightBob) heightAlice else heightBob

// Uses else if as an expression:
val heightLimit = 150
val heightOrLimit = if (heightLimit > heightAlice) heightLimit else if (heightAlice > heightBob) heightAlice else heightBob

println("Taller height is $taller")
// Taller height is 175
println("Height or limit is $heightOrLimit")
// Height or limit is 175

Each branch in an if expression can be a block, where the value of the last expression becomes the result:

kotlinval heightAlice = 160
val heightBob = 175

val taller = if (heightAlice > heightBob) {
    print("Choose Alice\n")
    heightAlice
} else {
    print("Choose Bob\n")
    heightBob
}

println("Taller height is $taller")

#When expressions and statements

when is a conditional expression that runs code based on multiple possible values or conditions. It's similar to the switch statement in Java, C, and other languages. when evaluates its argument and compares the result against each branch in order until one branch condition is satisfied.

kotlinval userRole = "Editor"
when (userRole) {
    "Viewer" -> print("User has read-only access")
    "Editor" -> print("User can edit content")
    else -> print("User role is not recognized")
}
// User can edit content

You can use when either as an expression or a statement.

TypeDescriptionExample
ExpressionReturns a value assigned to a variable.val text = when(x) { 1 -> "one"; else -> "other" }
StatementCompletes an action without returning a result.when(x) { 1 -> print("one"); else -> print("other") }

Secondly, you can use when with or without a subject. Using a subject usually makes your code more readable.

#Statements

If you use when as a statement, you don't need to cover all possible cases (it is not required to be exhaustive).

kotlinval deliveryStatus = "OutForDelivery"
when (deliveryStatus) {
    // Not all cases are covered
    "Pending" -> print("Your order is being prepared")
    "Shipped" -> print("Your order is on the way")
}

#Expressions

If you use when as an expression, you must cover all possible cases. If you don't, the compiler throws an error. If your subject is a Boolean, enum class, or sealed class, you can often cover all cases without an else branch.

kotlinenum class Bit {
    ZERO, ONE
}

fun main() {
    val numericValue = when (getRandomBit()) {
        // No else branch needed: all cases covered
        Bit.ZERO -> 0
        Bit.ONE -> 1
    }
}

If your when expression doesn't have a subject, you must have an else branch:

kotlinval message = when {
    localFileSize > remoteFileSize -> "Local file is larger"
    localFileSize < remoteFileSize -> "Local file is smaller"
    else -> "Files are the same size"
}

#Other ways to use when


#Guard conditions

Guard conditions allow you to include more than one condition to branches using the if keyword. They are available when when has a subject.

kotlinwhen (animal) {
    is Animal.Dog -> feedDog()
    is Animal.Cat if !animal.mouseHunter -> feedCat()
    else -> println("Unknown animal")
}

#For loops

Use the for loop to iterate through a collection, array, or range:

kotlinfor (item in collection) {
    println(item)
}

#Ranges

#Arrays and Indices

kotlin// Using indices
for (i in routineSteps.indices) {
    println(routineSteps[i])
}

// Using withIndex()
for ((index, value) in routineSteps.withIndex()) {
    println("Item at $index is $value")
}

#While loops

while and do-while loops run continuously while a condition is satisfied.

kotlin// While loop
while (carsInGarage < maxCapacity) {
    carsInGarage++
}

// Do-while loop
do {
    roll = Random.nextInt(1, 7)
} while (roll != 6)

#Break and continue

Kotlin supports traditional break (to terminate a loop) and continue (to skip to the next iteration).