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

bookIf–Else Expressions

Swipe um das Menü anzuzeigen

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?

Wählen Sie die richtige Antwort aus

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 2. Kapitel 2

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 2. Kapitel 2
some-alt