Kotlin when Expression Explained (2025 Guide to Smarter Conditional Logic)
Replace clunky if..else chains with Kotlin’s when expression for cleaner, more readable conditional logic! ๐ It’s a powerful, flexible tool that selects a code path based on conditions, acting like a modernized switch with superpowers. ๐
- ๐ Basic When: Match values for simple branching. ✅
- ๐ When as Expression: Return values directly. ๐ฆ
- ⚖️ Advanced Features: Ranges, type checks, and more. ๐
Basic When Expression ๐
The when expression matches a value against branches, executing the first matching block. It’s Kotlin’s sleek alternative to Java’s switch! ๐
fun main() {
val day = 4 // ๐ข Day number
val result = when (day) { // ๐ Match day
1 -> "Monday" // ๐
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
else -> "Invalid day." // ๐ซ Fallback
}
println(result) // Outputs: Thursday ๐
}
How It Works:
- ๐ Single Check: The input (day) is evaluated once. ⚖️
- ➡️ Arrow Syntax: -> links conditions to results. ๐
- ✅ Match and Run: Executes the matching branch. ๐
- ๐ซ else: Handles unmatched cases, required for expressions. ๐ฆ
When as an Expression ๐ฆ
Like if, when can return a value when assigned to a variable, making it ultra-concise! ๐ฏ Use else to ensure all cases are covered.
fun main() {
val x: Any = 13.37 // ๐ข Any type
val result = when (x) { // ๐ Type checking
is Int -> "is an Int" // ✅ Int match
!is Double -> "is not Double" // ❌ Not Double
is String -> "is a String" // ๐ String match
else -> "is none of the above" // ๐ซ Fallback
}
println("$x $result") // Outputs: 13.37 is none of the above ✨
}
Expression Benefits:
- ๐ฆ Return Value: Assigns results directly to variables. ✅
- ⚡ Compact: Replaces verbose conditionals. ๐งน
- ๐ Versatile: Handles types, values, and conditions. ๐
Advanced When Features: Ranges, Multiple Values, and More ๐ก
The when expression shines with advanced capabilities like ranges, multiple value matching, and type checks. ๐
- ๐ Multiple Values: Match multiple options (e.g., 1, 2, 3). ๐ข
- ๐ Ranges: Use in or !in for ranges (e.g., in 1..10). ๐
- ๐ Type Checks: Use is or !is for type matching. ๐งฉ
- ⚡ Condition Blocks: Evaluate complex conditions without an argument. ๐ง
fun main() {
val month = 3 // ๐ข Month number
when (month) { // ๐ Match with ranges
1, 2, 3 -> println("Spring ๐ธ") // ๐ Multiple values
in 4..6 -> println("Summer ☀️") // ๐ Range
in 7..9 -> println("Fall ๐")
in 10..12 -> println("Winter ❄️")
else -> println("Invalid Month ๐ซ")
} // Outputs: Spring ๐ธ ๐
val value: Any = "Kotlin" // ๐ข Any type
when (value) { // ๐ Type checking
is String -> println("String of length ${value.length}") // ๐
is Int -> println("Integer: $value")
else -> println("Unknown type")
} // Outputs: String of length 6 ๐
}
Advanced Tip: Combine ranges and type checks for powerful, readable logic! ๐
When Without an Argument ๐ง
Use when without an argument to evaluate arbitrary conditions, replacing complex if-else ladders. ⚖️
fun main() {
val score = 85 // ๐ข Student score
val grade = when { // ๐ No argument
score >= 90 -> "A" // ๐ฅ
score >= 80 -> "B" // ๐ฅ
score >= 70 -> "C" // ๐ฅ
else -> "D" // ๐
}
println("Grade: $grade") // Outputs: Grade: B ๐
}
No-Argument Benefit: Simplifies condition-heavy logic into a clean, expressive format. ๐งน
When with Null Safety ๐จ
Kotlin’s null safety integrates seamlessly with when to handle nullable types safely. ๐ก️
fun main() {
val name: String? = null // ๐ Nullable string
when (name) { // ๐ Check for null
null -> println("Name is null") // ๐ซ
else -> println("Name: $name, Length: ${name.length}") // ✅
} // Outputs: Name is null ๐
}
Null Safety Tip: Use when with null checks or combine with ?. and ?: for robust handling. ⚡
Provided Example: If vs. When ๐
The provided code compares if and when, showcasing when’s elegance. Here’s an enhanced version with detailed comments:
fun main() {
// ๐ ️ If Statements
var age = 17 // ๐ข Age input
if (age >= 21) { // ๐ Check drinking age
print("Now you may drink in the US ๐บ") // ๐ฅ
} else if (age >= 18) { // ๐ Check voting age
print("Now you may vote ๐ณ️") // ๐ณ️
} else if (age >= 16) { // ๐ Check driving age
print("You now may drive ๐") // ๐
} else { // ๐ Fallback
print("You're too young ๐ถ") // ๐ถ
} // Outputs: You now may drive ๐ ๐
// ๐ When Expression
var season = 3 // ๐ข Season number
when (season) { // ๐
Match season
1 -> println("Spring ๐ธ")
2 -> println("Summer ☀️")
3 -> println("Fall ๐")
4 -> println("Winter ❄️")
else -> println("Invalid Season ๐ซ")
} // Outputs: Fall ๐ ๐
// ๐ When with ranges
var month = 3 // ๐ข Month number
when (month) { // ๐ Match with ranges
1, 2, 3 -> println("Spring ๐ธ") // ๐ Multiple values
in 4..6 -> println("Summer ☀️") // ๐ Range
in 7..9 -> println("Fall ๐")
in 10..12 -> println("Winter ❄️")
else -> println("Invalid Month ๐ซ")
} // Outputs: Spring ๐ธ ๐
// ๐ฏ If-to-When Challenge
when (age) { // ๐ Convert if to when
!in 0..20 -> print("Now you may drink in the US ๐บ") // ๐ฅ
in 18..20 -> print("Now you may vote ๐ณ️") // ๐ณ️
16, 17 -> print("You now may drive ๐") // ๐
else -> print("You're too young ๐ถ") // ๐ถ
} // Outputs: You now may drive ๐ ๐
}
Comparison Insight: when is more concise and readable for value matching or range checks compared to if. ⚖️
Practical Use Case: Menu System ๐ฝ️
Use when to build a user-friendly menu system for apps or scripts. ๐ ️
fun main() {
val choice = 2 // ๐ข User menu selection
val action = when (choice) { // ๐ Match menu option
1 -> "Start Game ๐ฎ"
2 -> "View Scores ๐"
3 -> "Settings ⚙️"
4 -> "Exit ๐ช"
else -> "Invalid Option ๐ซ"
}
println(action) // Outputs: View Scores ๐ ๐
}
Menu Tip: Combine when with user input for interactive, dynamic systems. ๐ฏ
when vs. if vs. Java switch ⚖️
Compare when with if and Java’s switch to choose the right tool. ๐
fun main() {
val code = 2 // ๐ข Input code
// Using if
val ifResult = if (code == 1) "Low" else if (code == 2) "Medium" else "High"
// Using when
val whenResult = when (code) { // ๐ Cleaner
1 -> "Low"
2 -> "Medium"
else -> "High"
}
println("if: $ifResult") // Outputs: if: Medium ๐
println("when: $whenResult") // Outputs: when: Medium ๐
}
- ๐ when: Best for value matching, ranges, or type checks. ๐
- ๐ ️ if: Ideal for complex or nested conditions. ๐งฉ
- ๐ซ Java switch: Less flexible, no ranges or type checks, requires break. ๐
Comparison Tip: Use when for clean, multi-branch logic; reserve if for intricate conditions. ⚖️
Best Practices for When Expressions ✅
- ๐งน Keep It Simple: Use when for value matching or ranges to avoid clutter. ๐
- ✅ Include else: Ensure all cases are covered when assigning to variables. ๐ซ
- ๐ Use Ranges: Leverage in and !in for numeric or enum ranges. ๐ข
- ๐ Type Safety: Use is for type checks with smart casts. ๐งฉ
- ๐ก️ Null Handling: Check for null explicitly in when branches. ๐จ
- ๐ Readable Code: Add comments for complex when logic to aid maintenance. ๐ง
Frequently Asked Questions (FAQ) ❓
- Why use when instead of if? ๐ค
when is more concise for value matching, ranges, or type checks, reducing boilerplate compared to if-else ladders. ๐ - Is else mandatory in when expressions? ๐ซ
Yes, when assigning when to a variable to ensure all paths return a value; optional otherwise. ๐ฆ - Can when handle ranges and types? ๐
Yes, use in for ranges (e.g., in 1..10) and is for type checks (e.g., is String). ๐ - How does when differ from Java’s switch? ⚖️
when supports ranges, type checks, and expressions, doesn’t need break, and is more flexible than switch. ๐ - Can when be used without an argument? ๐ง
Yes, when without an argument evaluates conditions like if-else, ideal for complex logic. ⚡ - How does when handle nulls? ๐จ
Check null explicitly in a branch or use null-safe operators (?., ?:) for nullable inputs. ๐ก️
Comments
Post a Comment