Control 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
1234567891011121314151617181920212223242526272829package 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.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat