Welcome to The Coding College! In this tutorial, we’ll explore the when
expression in Kotlin, one of its most versatile tools for decision-making. The when
expression is like a more powerful version of switch
in other programming languages, allowing you to handle multiple conditions effectively.
What is when
in Kotlin?
The when
expression in Kotlin evaluates a value or a condition and executes the corresponding block of code. It is concise, readable, and eliminates the need for multiple if...else if
statements.
Basic Syntax:
when (value) {
condition1 -> // code to execute
condition2 -> // code to execute
else -> // code to execute if none of the conditions match
}
Kotlin when
Example
Here’s a basic example of using when
to evaluate an integer value:
fun main() {
val day = 3
val dayName = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
else -> "Invalid day"
}
println("Day: $dayName")
}
Output:
Day: Wednesday
Features of when
in Kotlin
1. Multiple Conditions in a Single Branch
You can group multiple conditions in a single branch by separating them with commas.
Example:
fun main() {
val fruit = "Apple"
when (fruit) {
"Apple", "Banana", "Mango" -> println("This is a fruit.")
else -> println("Unknown item.")
}
}
Output:
This is a fruit.
2. Using when
as an Expression
The when
block can return a value, making it a great alternative to if...else
constructs.
Example:
fun main() {
val age = 20
val category = when {
age < 13 -> "Child"
age in 13..19 -> "Teenager"
age >= 20 -> "Adult"
else -> "Unknown"
}
println("Category: $category")
}
Output:
Category: Adult
3. Checking Types in when
You can use when
to check the type of a variable using is
.
Example:
fun main() {
val obj: Any = "Hello"
when (obj) {
is String -> println("It's a String!")
is Int -> println("It's an Integer!")
else -> println("Unknown type.")
}
}
Output:
It's a String!
Practical Examples of when
Example 1: Grade Evaluation
fun main() {
val marks = 85
val grade = when (marks) {
in 90..100 -> "A+"
in 80..89 -> "A"
in 70..79 -> "B"
in 60..69 -> "C"
else -> "F"
}
println("Grade: $grade")
}
Output:
Grade: A
Example 2: Days of the Week
fun main() {
val day = "Sunday"
when (day) {
"Saturday", "Sunday" -> println("It's the weekend!")
else -> println("It's a weekday.")
}
}
Output:
It's the weekend!
Example 3: Role-Based Access
fun main() {
val role = "Admin"
val accessLevel = when (role) {
"Admin" -> "Full Access"
"Editor" -> "Edit Access"
"Viewer" -> "Read-Only Access"
else -> "No Access"
}
println("Access Level: $accessLevel")
}
Output:
Access Level: Full Access
Best Practices for Using when
- Use
when
for Readability: Replace lengthyif...else if
chains withwhen
for better clarity. - Avoid Redundant Conditions: Simplify your conditions and use ranges where applicable.
- Default Case with
else
: Always include anelse
branch to handle unexpected cases.
Learn More on The Coding College
The when
expression is a powerful tool in Kotlin that simplifies decision-making in your code. Explore more Kotlin tutorials on The Coding College to learn how to write clean, efficient, and maintainable programs.
Conclusion
The when
expression in Kotlin is a versatile and elegant way to handle multiple conditions. By mastering when
, you can write more concise and effective code, making your programs easier to understand and maintain.