If as an Expression
Свайпніть щоб показати меню
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,
ifis an expression that produces a value; - You can assign the result of an
ifexpression to a variable; - This feature leads to more concise and readable code.
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат