Utilize Control Flow in Kotlin

May 22 2024 · Kotlin 1.9.23, Android 14, Kotlin Playground

Lesson 03: Loop Code

Demo

Episode complete

Play next episode

Next

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Open the starter project in the playground and look at the very top. For the readability of this screencast, it shows only the code needed for the given task. Showing the entire sample project code at once would be overwhelming.

    println("For loop with range 1..3")
    for (i in 1..3) {
        println("Cleaning classroom $i...")
    }
    println("For loop with range 1..<3")
    for (i in 1..<3) {
        println("Cleaning classroom $i...")
    }
    println("For loop with range 3..1")
    for (i in 3..1) {
        println("Cleaning classroom $i...")
    }
    println("For loop with range 3 downTo 1")
    for (i in 3 downTo 1) {
        println("Cleaning classroom $i...")
    }
    println("Count of classrooms to clean:")
    val classroomsToClean = args.firstOrNull()?.toIntOrNull()
        ?: throw IllegalArgumentException("Invalid input, please enter a number")

    val cleanedClassrooms = mutableListOf<Int>()
    println()
    println("While loop")
    while (cleanedClassrooms.size < classroomsToClean) {
        val currentClassroom = cleanedClassrooms.size + 1
        println("Cleaning classroom $currentClassroom...")
        cleanedClassrooms.add(currentClassroom)
    }
    println("Do-while loop")
    cleanedClassrooms.clear()
    do {
        val currentClassroom = cleanedClassrooms.size + 1
        println("Cleaning classroom $currentClassroom...")
        cleanedClassrooms.add(currentClassroom)
    } while (cleanedClassrooms.size < classroomsToClean)
    println("Continue statement")
    for (currentClassroom in 1..3) {
        if (currentClassroom == 2) {
            println("Skipping classroom $currentClassroom...")
            continue
        }
        println("Cleaning classroom $currentClassroom...")
    }
    println("Break statement")
    for (currentClassroom in 1..3) {
        if (currentClassroom == 2) {
            println("Breaking on classroom $currentClassroom...")
            break
        }
        println("Cleaning classroom $currentClassroom...")
    }
See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion