Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Control Flow Constructs | Kotlin Idioms and Control Flow
Kotlin for Java Developers

bookControl Flow Constructs

Свайпніть щоб показати меню

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

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 3

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 3. Розділ 3
some-alt