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

bookControl Flow Constructs

Sveip for å vise menyen

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

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 3

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 3. Kapittel 3
some-alt