— Kotlin, Programming, Android Development — 2 min read
Kotlin is a modern, concise, and expressive programming language that has gained popularity among programmers for its simplicity and ease of use. One of the core features that makes Kotlin stand out from other programming languages is the 'when' expression, which allows you to perform conditional operations in a concise and readable way. In this article, we will explore the power of Kotlin's 'when' expression and how you can use it to simplify your code.
The 'when' expression is used to perform conditional operations based on the value of a variable or an expression. It works similar to the switch statement in Java or C++, but with some added features that make it more flexible and powerful. Here's the basic syntax of the 'when' expression:
1when (variable) {2 value1 -> operation1()3 value2 -> operation2()4 ...5 else -> defaultOperation()6}
In this syntax, variable
is the variable or expression whose value you want to match against different cases, value1
, value2
, etc. are the values that you want to compare against the variable, and operation1()
, operation2()
, etc. are the operations that you want to perform if the corresponding value matches the variable. You can have any number of cases, and you can also include an optional else
branch that will be executed if none of the values match.
The 'when' expression can also be used as an expression, which means it can return a value. Here's an example:
1val result = when (variable) {2 value1 -> operation1()3 value2 -> operation2()4 ...5 else -> defaultOperation()6}
In this code snippet, the value of result
will be the result of the operation that matches the value of variable
. If none of the values match, it will be the result of the default operation.
Let's see some examples of how you can use Kotlin's 'when' expression to simplify your code and make it more readable.
Suppose you have a variable score
that represents the score of a player in a game, and you want to perform different operations based on the score. Here's how you can do it using Kotlin's 'when' expression:
1when (score) {2 in 0..50 -> println("You need to practice more.")3 in 51..70 -> println("Not bad, but you can do better.")4 in 71..90 -> println("Good job!")5 in 91..100 -> println("Excellent!")6 else -> throw IllegalArgumentException("Score must be between 0 and 100.")7}
In this code snippet, we are checking the value of score
against multiple ranges using the in
operator. For example, if score
is between 0 and 50, we print the message "You need to practice more." Similarly, we have different messages for different score ranges. If the score is outside the range of 0 to 100, we throw an exception.
Kotlin's 'when' expression can also be used to match against different types. Suppose you have a variable value
that can be of different types, and you want to perform different operations based on the type of value
. Here's how you can do it using Kotlin's 'when' expression:
1when (value) {2 is String -> println("The value is a string.")3 is Int -> println("The value is an integer.")4 is Double -> println("The value is a double.")5 else -> throw IllegalArgumentException("Unsupported type.")6}
In this code snippet, we are checking the type of value
using the is
operator. If value
is a string, we print the message "The value is a string." Similarly, we have different messages for different types. If the type of value
is unsupported, we throw an exception.
As mentioned earlier, Kotlin's 'when' expression can also be used as an expression, which means it can return a value. Let's see an example of how you can use'when' as an expression:
1val message = when (dayOfWeek) {2 Calendar.MONDAY -> "It's Monday!"3 Calendar.TUESDAY -> "It's Tuesday!"4 Calendar.WEDNESDAY -> "It's Wednesday!"5 Calendar.THURSDAY -> "It's Thursday!"6 Calendar.FRIDAY -> "It's Friday!"7 else -> "It's a weekend day."8}
In this code snippet, we are using Kotlin's 'when' expression to return a different message based on the day of the week. If dayOfWeek
is Monday, we return the message "It's Monday!", and so on. If dayOfWeek
is not any of the weekdays, we return the message "It's a weekend day." The value of message
will be the result of the operation that matches the value of dayOfWeek
.
Kotlin's 'when' expression is a powerful feature that can simplify your code and make it more readable. It allows you to perform conditional operations in a concise and flexible way, and it can also be used as an expression that returns a value. By mastering the 'when' expression, you can write cleaner and more maintainable code.