Job-ready Online Courses: Click, Learn, Succeed, Start Now!
Kotlin, a contemporary programming language, empowers developers with a plethora of efficient features. Among these features, the ‘when’ expression stands out as a robust decision-making tool. In this article, we will explore Kotlin’s ‘when’ expression in depth, examining its syntax and demonstrating its effectiveness through relevant code snippets and examples.
Kotlin When Expression Syntax and Usage:
The ‘when’ expression in Kotlin can be likened to an advanced version of the traditional ‘switch’ statement found in other programming languages. It boasts a simple and flexible syntax, enabling developers to handle multiple conditions concisely and readably. Let’s take a look at the fundamental structure of a ‘when’ expression:
when (variable) {
condition1 -> {
// Code block executed when condition1 is met
}
condition2 -> {
// Code block executed when condition2 is met
}
// Additional conditions and code blocks can be added
else -> {
// Code block executed when none of the conditions are met
}
}
The ‘when’ expression commences with the keyword ‘when’, followed by the variable or expression to be evaluated. Each condition is specified using the ‘->’ operator, followed by the code block to be executed when the condition is satisfied. The ‘else’ branch, although optional, serves as a fallback when none of the conditions match.
Example 1: Handling Different Input Types in Kotlin
fun handleInput(input: Any) {
when (input) {
is Int -> println("Hey Mugdha! The input is an integer.")
is String -> println("Hey Mugdha! The input is a string.")
is Double -> println("Hey Mugdha! The input is a double.")
else -> println("Hey Mugdha! The input type is unknown.")
}
}
Input:
“Hello”
Output:
In this example, the ‘when’ expression is utilized to determine the type of the ‘input’ parameter. Depending on the type, an appropriate message is displayed.
Example 2: Simplifying Ranges
fun evaluateScore(score: Int) {
val grade = when (score) {
in 90..100 -> "A"
in 80 until 90 -> "B"
in 70 until 80 -> "C"
in 60 until 70 -> "D"
else -> "F"
}
println("Dear Mugdha, your grade is $grade.")
}
Input: 85
Output:
In this example, the ‘when’ expression is employed to calculate Mugdha’s grade based on her score. Utilizing ranges, the code becomes more concise and understandable.
Example 3: Enum Handling in Kotlin
enum class DayOfWeek {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
fun getWeekdayName(day: DayOfWeek) {
val name = when (day) {
DayOfWeek.MONDAY -> "Monday"
DayOfWeek.TUESDAY -> "Tuesday"
DayOfWeek.WEDNESDAY -> "Wednesday"
DayOfWeek.THURSDAY -> "Thursday"
DayOfWeek.FRIDAY -> "Friday"
DayOfWeek.SATURDAY -> "Saturday"
DayOfWeek.SUNDAY -> "Sunday"
}
println("Hello Mugdha! It's $name today.")
}
Input: Wednesday
Output:
In this example, the ‘when’ expression is employed to convert an enum value representing a day of the week into its corresponding name. With a warm greeting, we inform Mugdha about the specific day.
More Use cases for Kotlin When Expression
The ‘when’ expression commences with the keyword ‘when’, followed by the variable or expression to be evaluated. Each condition is specified using the ‘->’ operator, followed by the code block to be executed when the condition is satisfied. The ‘else’ branch, although optional, serves as a fallback when none of the conditions match.
Using when as a statement with else:
fun handleInput(input: Any) {
when (input) {
is Int -> println("The input is an integer.")
is String -> println("The input is a string.")
is Double -> println("The input is a double.")
else -> println("The input type is unknown.")
}
}
Input: “Hello”
Output:
Explanation:
The ‘handleInput’ function takes an input of type `Any` and uses the ‘when’ expression to determine its type. In this example, the input is a string (“Hello”), so the corresponding message “The input is a string” is printed.
Using when as a statement without else:
fun evaluateScore(score: Int) {
val grade = when (score) {
in 90..100 -> "A"
in 80 until 90 -> "B"
in 70 until 80 -> "C"
in 60 until 70 -> "D"
else -> "F"
}
println("Your grade is $grade.")
}
Input: 85
Output:
Explanation:
The ‘evaluateScore’ function takes a score as an input and uses the ‘when’ expression to determine the corresponding grade. In this example, the score is 85, which falls in the range of 80 to 89, so the grade “B” is assigned to the ‘grade’ variable. The message “Your grade is B” is then printed.
Different ways to use them when block in Kotlin:
Combine multiple branches in one using a comma:
fun checkNumber(number: Int) {
when (number) {
0, 1 -> println("Number is either 0 or 1.")
2 -> println("Number is 2.")
else -> println("Number is neither 0, 1, nor 2.")
}
}
Input: 2
Output:
Explanation:
The ‘checkNumber’ function takes a number as input and uses the ‘when’ expression to check its value. In this example, the input is 2, so the branch that matches 2 is executed, printing the message “Number is 2.”
Check the input value in the range or not:
fun checkRange(number: Int) {
when (number) {
in 1..10 -> println("Number is between 1 and 10.")
!in 1..10 -> println("Number is not between 1 and 10.")
}
}
Input: 7
Output:
Explanation:
The ‘checkRange’ function takes a number as input and uses the ‘when’ expression to check if it falls within the range of 1 to 10 (inclusive). In this example, the input value is 7, which satisfies the condition, so the message “Number is between 1 and 10” is printed.
Check if a given variable is of a certain type or not:
fun checkType(value: Any) {
when (value) {
is Int -> println("Value is of type Int.")
is String -> println("Value is of type String.")
else -> println("Value is of an unknown type.")
}
}
Input: “Hello”
Output:
Explanation:
The ‘checkType’ function takes a value of type `Any` and uses the ‘when’ expression to check its type. In this example, the value is a string, so the message “Value is of type String” is printed.
Using when as an expression:
fun isPositive(number: Int): Boolean {
return when {
number > 0 -> true
else -> false
}
}
Input: -5
Output:
Explanation:
The ‘isPositive’ function takes a number as input and uses the ‘when’ expression without an expression to check if the number is positive. If the number is greater than 0, the expression evaluates to true; otherwise, it evaluates to false. In this example, the input number is -5, which is not greater than 0, so the output is false.
Using when without an expression:
fun checkNumberType(number: Int) {
when {
number < 0 -> println("Number is negative.")
number > 0 -> println("Number is positive.")
else -> println("Number is zero.")
}
}
Input: 7
Output:
Explanation:
The ‘checkNumberType’ function takes a number as input and uses the ‘when’ expression without an expression to check its value. In this example, when the number is positive, the message “Number is positive” is printed.
Multiple statements of when using braces:
fun checkValue(value: Int) {
when (value) {
0 -> {
println("Value is 0.")
println("It's a special case.")
}
1, 2 -> {
println("Value is either 1 or 2.")
println("It's another special case.")
}
else -> println("Value is not 0, 1, or 2.")
}
}
Input: 0
Output:
Explanation:
The ‘checkValue’ function takes a value as input and uses the ‘when’ expression with multiple statements enclosed in curly braces for each branch. In this example, the input value is 0, which matches the first branch. The two print statements inside the curly braces are executed, resulting in the messages “Value is 0” and “It’s a special case” being printed.
Using ‘when in the range:
fun checkTemperature(temperature: Int) {
when (temperature) {
in 0..10 -> println("It's very cold.")
in 11..20 -> println("It's cold.")
in 21..30 -> println("It's moderate.")
else -> println("It's hot.")
}
}
Input: 25
Output:
Explanation:
The ‘checkTemperature’ function takes a temperature value as input and uses the ‘when’ expression to determine the corresponding temperature range. In this example, the input temperature is 25, which falls in the range of 21 to 30, so the message “It’s moderate” is printed.
Conclusion
Kotlin’s ‘when’ expression offers developers a versatile and concise approach to handling diverse conditions. Simplifying the code and enhancing readability enables efficient handling of various scenarios. This article has shed light on the power of Kotlin’s ‘when’ expression, empowering you to make informed decisions in your programming journey.
