Design Converter
Education
Last updated on Dec 12, 2024
Last updated on Dec 12, 2024
The 'when' expression is one of Kotlin's most powerful features, designed to simplify condition handling with a clean and concise syntax. It replaces the traditional switch statement found in other languages like Java or C++, offering much more flexibility and ease of use. If you've ever struggled with writing multiple branches of conditional logic or keeping your code readable when handling multiple cases, Kotlin when expression is your new best friend.
In this blog, you'll learn the ins and outs of 'when' expressions, from their syntax to practical examples, and understand how they can replace complex if statements or traditional switch statements. Whether you're working with strings, ranges, or particular types, this blog will help you master Kotlin when for better and more readable code.
At its core, the 'when' expression in Kotlin is a replacement for the switch statement found in other languages. Unlike a switch statement, the 'when' expression is more flexible, supports complex expressions, and can be used as both a statement and an expression.
Here’s an example of a simple 'when' expression:
1fun main() { 2 val day = 5 3 val result = when (day) { 4 1 -> "Monday" 5 2 -> "Tuesday" 6 3 -> "Wednesday" 7 4 -> "Thursday" 8 5 -> "Friday" 9 6, 7 -> "Weekend" // Combining multiple values 10 else -> "Invalid day" 11 } 12 println(result) 13}
Flexibility: You can compare a variable against constants, ranges, or even boolean expressions.
Exhaustive: When used as an expression, all possible cases must be covered, including the else branch.
Syntactic Sugar: Simplifies complex conditional logic into readable and compact code.
Multiple Conditions: You can handle multiple conditions in a single branch using commas.
While a 'when' expression returns a value, a 'when' statement is used to execute code without returning a result. Consider the difference:
The 'when' expression is assigned to a variable, ensuring it evaluates to a value.
1fun main() { 2 val number = 10 3 val result = when { 4 number < 0 -> "Negative" 5 number == 0 -> "Zero" 6 else -> "Positive" 7 } 8 println(result) // Output: Positive 9}
Here, you use 'when' to execute specific block of code without assigning a value.
1fun main() { 2 val number = 10 3 when { 4 number < 0 -> println("Number is Negative") 5 number == 0 -> println("Number is Zero") 6 else -> println("Number is Positive") 7 } 8}
To master the 'when' expression, it’s important to understand its key components:
Subject: The variable or expression being evaluated.
Branch Conditions: The conditions to match against the subject.
Branches: The block of code executed when a branch matches.
Else Branch: A mandatory fallback for unmatched cases when used as an expression.
Here’s an example demonstrating the anatomy:
1fun main() { 2 val grade = 85 3 when { 4 grade >= 90 -> println("A") 5 grade >= 80 -> println("B") 6 grade >= 70 -> println("C") 7 else -> println("Fail") 8 } 9}
The else branch ensures that your 'when' expression is exhaustive. Without it, Kotlin compiler throws an error if all possible cases aren’t handled. For instance:
1fun main() { 2 val animal = "Dog" 3 val sound = when (animal) { 4 "Cat" -> "Meow" 5 "Dog" -> "Bark" 6 "Cow" -> "Moo" 7 else -> "Unknown Sound" 8 } 9 println(sound) // Output: Bark 10}
The in operator is a game-changer when dealing with ranges. You can define branch conditions for values falling within specific ranges:
1fun main() { 2 val age = 25 3 val category = when (age) { 4 in 0..12 -> "Child" 5 in 13..19 -> "Teenager" 6 in 20..59 -> "Adult" 7 else -> "Senior" 8 } 9 println(category) // Output: Adult 10}
With 'when', you can also handle conditions based on the type of a variable:
1fun main() { 2 val obj: Any = "Kotlin" 3 when (obj) { 4 is String -> println("It's a String") 5 is Int -> println("It's an Int") 6 else -> println("Unknown Type") 7 } 8}
Using commas, you can handle multiple conditions in a single branch, improving readability:
1fun main() { 2 val char = 'A' 3 when (char) { 4 'A', 'E', 'I', 'O', 'U' -> println("Vowel") 5 else -> println("Consonant") 6 } 7}
Unlike traditional switch statements in Java, Kotlin’s 'when' expression is much more versatile:
• Supports ranges and type checking.
• Allows you to use complex boolean expressions.
• Provides exhaustive checks when used as an expression.
For example, here’s how a typical switch statement compares to Kotlin's when:
Switch Statement in Java:
1switch (day) { 2 case 1: return "Monday"; 3 case 2: return "Tuesday"; 4 default: return "Invalid day"; 5}
Kotlin 'when' Expression:
1val result = when (day) { 2 1 -> "Monday" 3 2 -> "Tuesday" 4 else -> "Invalid day" 5}
Use Exhaustive Conditions: Always include an else branch when the 'when' expression must return a value.x
Avoid Redundancy: Group multiple conditions using commas or ranges.
Keep It Readable: Avoid writing overly complex expressions within branches.
Prefer 'when' Over if Expression: When handling multiple branches, 'when' is cleaner and easier to maintain.
Kotlin 'when' expression is a powerful tool that can simplify your conditional logic. Whether you’re working with ranges, strings, or types, it provides a readable and flexible way to handle multiple branches of logic. Unlike traditional switch statements, 'when' expressions in Kotlin are more expressive and concise.
By mastering ‘when’, you’ll write cleaner, more efficient code that is easier to maintain. So the next time you face a decision-making scenario in your code, let Kotlin 'when' be your go-to choice! Happy coding!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.