Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ If–Else Expressions | If and If–Else Expressions
Control Flow in Kotlin

bookIf–Else Expressions

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

Introduction to If–Else Expressions in Kotlin

When you want your program to make decisions, you use if–else expressions. These let you run different code depending on whether a condition is true or false.

You write an if–else expression by checking a Boolean condition—something that is either true or false. If the condition is true, one block of code runs; if it is false, another block runs.

This is helpful when your program needs to react to different situations. For example, you might want to show a message if a user is logged in, or a different message if they are not.

Here is a simple structure of an if–else expression:

if (condition) {
    // Code runs if condition is true
} else {
    // Code runs if condition is false
}

You use if–else expressions to control the flow of your program and make it respond to different values or user actions.

Returning a Value

When you use an if–else expression, you can assign its result directly to a variable. The value returned is the result of the branch that is executed. This lets you write concise, readable code without repeating yourself.

Example:

val max = if (a > b) a else b

Here, max will be assigned the value of a if a is greater than b, or the value of b otherwise. You do not need a separate variable assignment inside each branch.

Why This Matters

  • Makes code shorter and clearer;
  • Reduces the need for temporary variables;
  • Encourages writing expressions instead of statements.

This feature is a key difference from many other languages, where if–else is only a statement and cannot directly return a value.

Main.kt

Main.kt

copy
question mark

Which statement about if–else expressions in Kotlin is true?

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

すべて明確でしたか?

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

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

セクション 2.  2

AIに質問する

expand

AIに質問する

ChatGPT

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

セクション 2.  2
some-alt