Kotlin When Expression

Topics Covered

Overview

The "when" in Kotlin is a powerful control flow construct in the Kotlin programming language. It is a versatile alternative to the traditional switch or if-else statements found in many other programming languages.

The "when" in Kotlin allows developers to write concise and expressive code to handle multiple conditional branches based on the value of a given expression. It is particularly useful when dealing with situations where there are multiple possible outcomes and each outcome requires a different set of actions.

"when" in Kotlin

One of the distinguishing features of "when" in Kotlin is its ability to serve both as an expression and a statement. As an expression, when in Kotlin evaluates to a value based on the matching branch, making it ideal for assigning values to variables or returning results. As a statement, when in Kotlin executes the corresponding branch based on the matched condition, providing an effective way to handle complex branching logic.

The when in Kotlin goes beyond basic value matching; it supports range checks using the in and !in operators, allowing developers to validate values within specific ranges. Additionally, when in Kotlin facilitates type checks with the is and !is operators, enabling identification of the type of variables.

By consolidating multiple branches in a single when block, developers can streamline common logic and conditions, enhancing code readability and maintainability. The else branch can be optionally included to handle cases when none of the specified branches match, ensuring that all possible scenarios are accounted for.

"when" can be Used in Two Ways

The when in Kotlin can be used in the following two ways:

  1. when as a statement
  2. when as an expression

Using "when" as a Statement with "else"

The when in Kotlin can function as a statement, with or without an else branch. When used as a statement, when in Kotlin sequentially compares the argument with the values in each branch, executing the corresponding branch where the condition matches. If none of the branches satisfy the condition, the else branch will be executed.

Consider the following code snippet.

Code:

Output:

Using "when" as a Statement without "else"

When used as a statement without an else branch, when in Kotlin compares the argument with the values of all individual branches sequentially. when in Kotlin executes the corresponding branch where the condition matches. If none of the branches satisfy the condition, it exits the block without any output to the system.

Note:
The when statement is generally used with an else branch to cover all possible cases explicitly, but in this case, it is being used without one.

Consider the following code snippet.

Code:

Explanation:

when expression checks vehicleName with the values of all individual branches and when it is unable to find a branch whose value matches with the argument in when i.e. "bike", it gives no output.

Using "when" as an Expression

When used as an expression, the value of the when statement corresponds to the branch whose condition is satisfied. It becomes the value of the overall expression. You can store this value in a variable or print it directly.

Consider the following code snippet.

Code:

Output:

Explanation:

In this example, the dayOfWeek variable holds the day number (1 to 7), and the dayName variable will be assigned the corresponding day name based on the when expression. When dayOfWeek variable is assigned 4, the when in Kotlin checks the branches sequentially for 4. Hence we get the output as "Today is Thursday".

Now let us consider the code in the above example without an else branch.

Code:

Output:

Explanation:

When dayOfWeek variable is assigned 8, the when in Kotlin checks the branches sequentially for 8. Since it does not match with any of the conditional branches in when and when do not have an else branch, the compiler gives the error as shown in the output above.

Different Ways to Use "when" the Block in Kotlin

Combine Multiple Branches in One Using Comma

We can utilize multiple branches in a single when block, separated by commas. When certain branches share common logic, we can merge them into a single branch.

Consider the following code snippet.

Code:

Output:

Explanation:

In this example, the isPlanet variable is set based on whether the largeBody matches any of the planet names. If it matches any of them, isPlanet will be true, and the corresponding message will be printed. Otherwise, it will be false, and the "is not a planet" message will be printed.

Check the Input Value in the Range or Not

By utilizing the in or !in operator, we can examine whether the argument falls within a specific range in a when block. In Kotlin, the in operator is employed to determine if a variable or property exists within a range. When the argument lies within the range, the in operator returns true; conversely, when the argument does not belong to the range, the !in operator returns true.

Consider the following code snippet.

Code:

Output:

Explanation:

In this example, the marks variable holds the marks obtained by a student (ranging from 0 to 100). The grade variable is assigned based on the marks using a when expression with the in operator to check which range the marks fall into. The corresponding grade is then printed based on the marks provided.

Check Given Variable is of a Certain Type or Not

By utilizing the is and !is operators, we can examine the type of a variable passed as an argument within a when block. If the variable is of type Integer, the is Int expression will yield true; otherwise, it will yield false.

Consider the following code snippet.

Code:

Output:

Explanation:

  1. We use the when expression with the is operator to check the type of the 'value' variable if it's Int, String, or Double. If it's none of these, the else block is executed.
  2. When you run the code, it will print "It's an Integer". because the 'value' is initialized with the Integer value 42.

Using "when" as a Replacement for an "if-else-if" Chain

when in Kotlin can serve as a substitute for if-else-if statements. In the absence of an explicit argument, the branch conditions are treated as boolean expressions. A branch is executed solely if its condition evaluates to true.

Consider the following code snippet.

Code:

Output:

Explanation:

  1. In this example, we have a variable named score which holds the value of a student's score.
  2. Instead of using if-else-if statements, we use the when expression without any argument. This allows us to evaluate the conditions as boolean expressions.
  3. The when expression checks the score against multiple conditions, stores the grade corresponding to the condition that matches, and prints in the console.

Check that a String Contains a Particular Prefix or Suffix

You can also check for a suffix or prefix in a given string using the following method. It returns true if the string contains the specified prefix or suffix, otherwise, it returns false.

Consider the following code snippet.

Code:

Output:

Explanation:

  1. In this example, we have a variable named text containing the string "Hello, World!".
  2. We use the when expression without an argument to check if text starts with the prefix "Hello". If it does, hasPrefix is set to true; otherwise, it is set to false.
  3. Similarly, we use the when expression without an argument to check if text ends with the suffix "World!". If it does, hasSuffix is set to true; otherwise, it is set to false.
  4. The program then prints the results, showing whether the string has the specified prefix and suffix.

Conclusion

  1. when in Kotlin is a versatile replacement for traditional switch-case statements and can be used to handle multiple branching scenarios based on the value of an expression.
  2. when in Kotlin can be used both as an expression and a statement, depending on the requirement. As an expression, it returns a value based on the matching branch, while as a statement, it executes the corresponding branch.
  3. when in Kotlin supports range checks using the in and !in operators, enabling easy validation of values within specific ranges. It also facilitates type checks using the is and !is operators, helping identify the type of variables.
  4. You can combine multiple branches within a single when block, separating them with commas, allowing you to consolidate common logic and conditions.
  5. You can include an else branch to handle cases where none of the specified branches match the value. This ensures that all possible cases are covered.
  6. By omitting the argument, when in Kotlin allows you to use boolean expressions as branch conditions, executing a branch if its condition evaluates to true.
  7. when expressions contribute to more concise and readable code, making it easier to understand complex branching logic.