Kotlin Decision Making
$count++; if($count == 1) { include "../mobilemenu.php"; } if ($count == 2) { include "../sharemediasubfolder.php"; } ?>
Decision making constructs allow your program to choose different paths of execution at runtime. Kotlin provides powerful if and when expressions, both of which can be used as statements or expressions, along with boolean logic to compose complex conditions.
1. if Expression vs Statement
In Kotlin, if can be used both as a statement (no return value) or as an expression (returns a value). This unifies conditional logic with assignment.
// if as statement
val x = 10
if (x % 2 == 0) {
println("Even")
} else {
println("Odd")
}
// if as expression
val parity = if (x % 2 == 0) "Even" else "Odd"
println(parity)
Output:
Even
Even
2. Multi-Branch if
You can chain multiple else if branches to handle more than two cases.
val score = 75
val grade = if (score >= 90) "A"
else if (score >= 80) "B"
else if (score >= 70) "C"
else if (score >= 60) "D"
else "F"
println(grade)
Output:C
3. when Expression
when replaces the traditional switch
and can match on values, ranges, types, or arbitrary expressions. It can also return a value.
val obj: Any = 42
val result = when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Int -> "Integer: $obj"
in 10..20 -> "Between 10 and 20"
else -> "Unknown"
}
println(result)
Output:Integer: 42
4. when Without Argument
Omitting the argument makes when act like if-else chains with arbitrary conditions.
val y = -5
when {
y > 0 -> println("Positive")
y == 0 -> println("Zero")
else -> println("Negative")
}
Output:Negative
5. Combining Conditions
Use logical operators && (AND), || (OR), and ! (NOT) to build compound tests.
val age = 25
if (age in 18..35 && age != 30) {
println("Target demographic")
} else {
println("Outside demographic")
}
Output:Target demographic
6. Smart Casts in when
Kotlin’s compiler automatically casts to a specific type after an is check, reducing boilerplate.
fun describe(x: Any) {
when (x) {
is String -> println("String of length ${x.length}")
is Int -> println("Double of Int = ${x * 2}")
else -> println("Unknown type")
}
}
describe("Kotlin")
describe(7)
Output:
String of length 6
Double of Int = 14
7. Nested Decision Constructs
You can nest if or when inside each other for deeper branching, but consider refactoring into functions for readability.
val temp = 30
if (temp > 0) {
when {
temp > 35 -> println("Heatwave")
temp > 25 -> println("Warm")
else -> println("Mild")
}
} else {
println("Freezing")
}
Output:Warm
8. Summary & Best Practices
- Favor expressions for if and when when you need a returned value.
- Use when for multi-branch matching, ranges, and type checks.
- Avoid deep nesting by extracting logic into well-named functions.
- Combine conditions sparingly to keep expressions clear.
- Leverage smart casts to reduce explicit casting.
- Include an else branch on when to ensure exhaustiveness.
- Document complex branches with comments or KDoc to clarify intent.