1. Overview

Kotlin consists of amazing features including the when() clause. This is Kotlin’s equivalent of the traditional switch() statement in many other languages.

However, Kotlin’s when() clause is far more versatile, allowing for complex comparisons using operators in the clause like less-than (<), less-than-or-equal-to (<=), greater-than-or-equal-to (>=), greater-than (>), and equals-to (==) to make our code more readable and efficient.

In this tutorial, we’ll explore using the when() clause with these comparison operators.

2. Using when() for Comparisons

We can use Kotlin’s when() clause for advanced comparisons. In the following subsections, we’ll discuss the less-than (<), less-than-or-equal-to (<=), greater-than-or-equal-to (>=), greater-than (>), and equals-to (==) operators together with the when() clause.

When using a when() clause, it must be exhaustive, meaning it contains branches for all possible types or comparisons of its subject. When we’re working with unrestricted types such as an Int or String, we’ll finish the when() clause with an else branch to cover all possible cases.

2.1. The Equals-To Comparison

The base comparison for the when() clause is equality, which means that when we use a when() expression to compare the value of an expression or variable with a set of cases, Kotlin implicitly uses the equality comparison (==) when no other operator is present. As a result, we don’t need to explicitly use the == operator in our when() expressions for equality.

The equals-to (==) operator allows us to check if a value is equal to a specific case:

fun evaluateFruit(fruit: String): String {
    return when (fruit) {
        "apple" -> "It's an apple"
        "banana" -> "It's a banana"
        "orange" -> "It's an orange"
        else -> "It's something else"

Now, let’s verify our evaluateFruit() function:

fun testFruit() {
    assertEquals("It's an apple", evaluateFruit("apple"))
    assertEquals("It's a banana", evaluateFruit("banana"))
    assertEquals("It's an orange", evaluateFruit("orange"))
    assertEquals("It's something else", evaluateFruit("grape"))

This code defines a function called evaluateFruit() that takes a single input parameter, fruit. We’re using a when() expression to check the value of the fruit. Depending on the value, our evaluateFruit() function returns a sentence describing the value. For example, if the fruit is an “apple,” it returns “It’s an apple”.

2.2. The Less-Than-or-Equal-To Comparison

The less-than-or-equal-to (<=) operator allows us to check if a value is less than or equal to a specified threshold:

fun evaluateAge(age: Int): String {
    return when {
        age <= 0 -> "Invalid age"
        age <= 18 -> "Child"
        age <= 65 -> "Adult"
        else -> "Senior"

Let’s verify our evaluateAge() function:

fun lessThanEqualTest() {
    assertEquals("Invalid age", evaluateAge(-5))
    assertEquals("Child", evaluateAge(12))
    assertEquals("Senior", evaluateAge(70))

In this example, the evaluateAge() function uses the less-than-or-equal-to operator to determine whether a person is a “Child”, “Adult”, or “Senior” based on their age.

2.3. The Greater-Than-or-Equal-To Comparison

The greater-than-or-equal-to (>=) operator is used to check if a value is greater than or equal to a specified threshold:

fun determineDiscount(price: Double): String {
    return when {
        price >= 100.0 -> "20% discount"
        price >= 50.0 -> "10% discount"
        else -> "No discount"

Let’s take a look at how we can test our determineDiscount() function:

fun testDetermineDiscount() {
    assertEquals("10% discount", determineDiscount(75.0))
    assertEquals("20% discount", determineDiscount(120.0))
    assertEquals("No discount", determineDiscount(30.0))

In this code, the determineDiscount() function uses the greater-than-or-equal-to operator to decide the discount percentage a customer will receive based on the price of a product.

2.4. The Greater-Than Comparison

The greater-than (>) operator allows us to check if a value is greater than a specific threshold:

fun evaluateTemperature(temperature: Int): String {
    return when {
        temperature > 30 -> "Hot"
        else -> "Cold"

Our test code for our evaluateTemperature() function will be:

fun testEvaluateTemperature() {
    assertEquals("Hot", evaluateTemperature(35))
    assertEquals("Cold", evaluateTemperature(0))

In this code, we’re using the greater-than operator to compare temperature with the when() clause. Depending on the value of the temperature parameter, the evaluateTemperature() function will return “Hot” if the temperature is greater than 30, or else it will return “Cold”.

2.5. The Less-Than Comparison

To use the less-than (<) operator in a when() clause, we can create cases based on whether the given value is less than a specific threshold:

fun evaluateScore(score: Int): String {
    return when {
        score < 50 -> "Fail"
        score < 75 -> "Pass"
        score < 90 -> "Good"
        else -> "Excellent"

Let’s verify we can use the when() expression above in conjunction with the less-than operator:

fun testEvaluateScore() {
    assertEquals("Fail", evaluateScore(35))
    assertEquals("Pass", evaluateScore(60))
    assertEquals("Good", evaluateScore(85))

In this code, the evaluateScore() function uses the less-than operator in the when() clause to categorize the value of the score into different levels of achievement. Depending on the value of the score, it returns “Fail”, “Pass”, “Good”, or “Excellent”.

3. Handling Ranges

Kotlin’s when() clause can also work with ranges, which makes it even more versatile for handling comparisons. We can use the in operator to check if a value falls within a specified range:

fun evaluateAgeCategory(age: Int): String {
    return when (age) {
        in 0..5 -> "Infant"
        in 6..12 -> "Child"
        in 13..19 -> "Teenager"
        in 20..64 -> "Adult"
        in 65..Int.MAX_VALUE -> "Senior"
        else -> "Invalid age"

Let’s test our evaluateCategory() function:

fun testAgeCategories() {
    assertEquals("Infant", evaluateAgeCategory(3))
    assertEquals("Teenager", evaluateAgeCategory(14))
    assertEquals("Adult", evaluateAgeCategory(45))

In this example, the evaluateAgeCategory() function uses the in operator to check if the age falls within specific age ranges and then returns the corresponding age category. This approach simplifies our code and makes it more readable. The range comparison in (0..5) is inclusive, meaning that it includes both the values 0 and 5. So, if the age is 0 or 5, it will enter the first clause and be returned as “Infant”.

4. Benefits of Using when() for Comparisons

Using the when() clause for comparisons in Kotlin offers two major benefits:

  • The code becomes easier to understand. Each case clearly represents a specific condition, making the code self-documenting.
  • We can handle multiple conditions in a compact and efficient manner.

5. Conclusion

In this article, we’ve explored the basics of the when() clause and how it can be leveraged for various comparison scenarios. We’ve demonstrated how to use less-than, less-than-or-equal-to, greater-than, greater-than-or-equal-to, and equals-to operators to make decisions based on the values of variables.

We’ve also showcased the flexibility of the when() clause for handling ranges.

The full implementation of these examples is available over on GitHub.

Comments are closed on this article!