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

bookIf as an Expression

Glissez pour afficher le menu

What Does "If as an Expression" Mean?

In Kotlin, the if statement is not just a control flow statement—it is also an expression. This means that if can return a value, just like a variable or a function call. You can assign the result of an if expression directly to a variable.

How Is This Different from Java?

In Java and many other languages, if is only a statement. You cannot assign the result of an if directly to a variable. You must use extra lines of code to set the value:

int max;
if (a > b) {
    max = a;
} else {
    max = b;
}

In Kotlin, you can do this in one step:

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

Why Is This Useful?

  • Makes code shorter and clearer;
  • Reduces the risk of mistakes by keeping related logic together;
  • Encourages you to think in terms of expressions, not just actions.

Using If as an Expression

You can use if anywhere a value is needed. For example, you can return the result of an if expression from a function, or use it as part of a larger calculation. Both the then and else branches must return a value.

val result = if (score >= 60) "Pass" else "Fail"

Multi-Line If Expressions

If you need more logic in each branch, you can use curly braces. The last expression in each branch is the value returned:

val message = if (user.isLoggedIn) {
    println("Welcome back!")
    "User logged in"
} else {
    println("Please log in.")
    "User not logged in"
}

Key Takeaways

  • In Kotlin, if is an expression that produces a value;
  • You can assign the result of an if expression to a variable;
  • This feature leads to more concise and readable code.
question mark

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

Sélectionnez la réponse correcte

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 2. Chapitre 5

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

Section 2. Chapitre 5
some-alt