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

Popular posts from this blog

Creating Beautiful Card UI in Flutter

Jetpack Compose - Card View