If–Else Expressions
Svep för att visa menyn
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
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal