Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ When as an Expression | Advanced Conditional Logic
Control Flow in Kotlin

bookWhen as an Expression

メニューを表示するにはスワイプしてください

What Is a 'when' Expression?

A 'when' expression in Kotlin is a flexible way to handle multiple conditions. It is similar to a switch statement in Java, but more powerful and concise. You use it to choose what your code should do based on different values or conditions.

How 'when' Expressions Work

  • You provide a value or condition to the when keyword;
  • Each branch checks if the value matches a specific case;
  • The first matching branch runs its code block;
  • If no branches match, the else branch runs (if provided).

Using 'when' as an Expression

A 'when' expression can return a value. You can assign the result of a when directly to a variable:

val result = when (number) {
    1 -> "One"
    2 -> "Two"
    else -> "Other"
}

Here, result will hold the string that matches the value of number.

Why Use 'when' Expressions?

  • Simplifies complex if-else chains;
  • Improves code readability and maintainability;
  • Supports matching multiple values, ranges, or conditions in each branch.
Main.kt

Main.kt

copy
question mark

Which statement about using when as an expression in Kotlin is true?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 3.  4

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 3.  4
some-alt