Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Control Flow Constructs | Kotlin Idioms and Control Flow
Kotlin for Java Developers

bookControl Flow Constructs

Swipe to show menu

Kotlin provides several expressive and concise control flow constructs that offer clear advantages for Java developers transitioning to the language. Three of the most notable are the with function for context operations, the when expression as a more flexible alternative to Java's switch, and idiomatic for loops that simplify iteration. Understanding these constructs will help you write cleaner and more idiomatic Kotlin code.

Main.kt

Main.kt

copy
1234567891011121314151617181920212223242526272829
package com.example data class Person(val name: String, val age: Int) fun main() { val person = Person("Alice", 30) // Using 'with' for context with(person) { println("Name: $name") println("Age: $age") } // Using 'when' as a powerful alternative to switch val grade = 'B' val result = when (grade) { 'A' -> "Excellent" 'B', 'C' -> "Good" 'D' -> "Needs Improvement" else -> "Unknown" } println("Grade result: $result") // Idiomatic for loop val numbers = listOf(1, 2, 3, 4, 5) for (n in numbers) { println("Number: $n") } }

In this example, the with function is used to operate on a Person object, allowing you to access its properties directly within the block, which improves readability by reducing repetition of the object name. The when expression replaces the traditional Java switch statement, supporting multiple matching values per branch and handling any type, not just primitives or enums. This makes branching logic more expressive and less error-prone. The for loop iterates over a collection in a concise way, removing the need for index management or iterators, and making the code easier to read and maintain.

question mark

What is a key advantage of the when expression over Java's switch?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Sectionย 3. Chapterย 3

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Sectionย 3. Chapterย 3
some-alt