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

bookIf–Else Expressions

Deslize para mostrar o menu

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?

Selecione a resposta correta

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 2

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Seção 2. Capítulo 2
some-alt