If–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
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo