Kotlin If Expression: Control Your Flow in 2025
Kotlin If Expression: Control Your Flow in 2025! π
The if expression returns a value and steers your program’s flow. π It comes in various forms in Kotlin.
- if-else expression π
- if-else if-else ladder expression ⚖️
- nested if expression π§©
if-else Expression π
The result of an if-else expression can be stored in a variable! π¦
Note: When using if as an expression, else is mandatory. π«
fun main(args: Array<String>) {
val num1 = 10
val num2 = 20
val result = if (num1 > num2) {
"$num1 is greater than $num2"
} else {
"$num1 is smaller than $num2"
}
println(result) // 10 is smaller than 20 π
}
Using if-else in a single-line expression mimics Java’s ternary operator—no ternary exists in Kotlin! ⚡
Note: You can skip curly braces {} for single-statement if blocks. π
fun main(args: Array<String>) {
val num1 = 10
val num2 = 20
val result = if (num1 > num2) "$num1 is greater than $num2" else "$num1 is smaller than $num2"
println(result) // 10 is smaller than 20 π
}
Key Features:
- ✅ Returns a value directly to a variable.
- ⚡ Replaces bulky conditionals with concise logic.
- π Works with any comparison (e.g., >=, <=).
- π Single-line form is super compact.
if-else if-else Ladder Expression ⚖️
fun main(args: Array<String>) {
val num = 10
val result = if (num > 0) {
"$num is positive"
} else if (num < 0) {
"$num is negative"
} else {
"$num is zero"
}
println(result) // 10 is positive π
}
Ladder Benefits:
- π Handles multiple conditions in sequence.
- π Each else if adds a new check.
- ✅ Final else catches all other cases.
- ⚡ Still returns a single value.
Nested if Expression π§©
fun main(args: Array<String>) {
val num1 = 25
val num2 = 20
val num3 = 30
val result = if (num1 > num2) {
val max = if (num1 > num3) {
num1
} else {
num3
}
"body of if " + max
} else if (num2 > num3) {
"body of else if " + num2
} else {
"body of else " + num3
}
println("$result") // body of if 30 π
}
Nested Power:
- 𧩠Layers if statements for deeper logic.
- π Compares multiple values step-by-step.
- π Finds max or min in nested conditions.
- ⚡ Combines checks into a single result.
..
Comments
Post a Comment