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

bookIf as an Expression

Desliza para mostrar el menú

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?

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 5

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Sección 2. Capítulo 5
some-alt