Sling Academy
Home/Kotlin/How to Use `when` Without an Argument in Kotlin

How to Use `when` Without an Argument in Kotlin

Last updated: November 30, 2024

Kotlin, a statically typed programming language, offers features that make coding concise and straightforward. One of these features is the when expression, which allows developers to easily branch their code depending on the conditions. The when keyword can be used with or without an argument, and in this article, we'll delve into how to use when without an argument.

Understanding the when Expression

The when expression in Kotlin operates similarly to the switch-case structure found in other languages, but it's much more powerful. When used without an argument, it behaves like a series of if-else if-else statements.

Why Use when Without an Argument?

  • Readability: Enhances the readability of conditional blocks.
  • Versatility: It supports complex conditions, types, and combines multiple conditions in a clean syntax.
  • Default Block: Like else in if conditions, it ensures there's a fall-back.

Basic Syntax


when {
    condition1 -> { /* code block for condition1 */ }
    condition2 -> { /* code block for condition2 */ }
    else -> { /* code block if no conditions match */ }
}

Here, each condition is checked sequentially. As soon as a true condition is found, its associated block is executed, and the rest are skipped.

Example: A Simple Weather Response System

Let's implement a simple weather response using the when expression without an argument.


fun respondToWeather(weather: String) {
    when {
        weather.contains("sunny", ignoreCase = true) -> println("It's a beautiful sunny day!")
        weather.contains("rainy", ignoreCase = true) -> println("Remember to take an umbrella.")
        weather.contains("cloudy", ignoreCase = true) -> println("It's a bit gloomy today.")
        else -> println("Weather is unpredictable today.")
    }
}

fun main() {
    respondToWeather("Sunny")  // Outputs: It's a beautiful sunny day!
    respondToWeather("rainy")  // Outputs: Remember to take an umbrella.
    respondToWeather("VERYCLOUDY")  // Outputs: It's a bit gloomy today.
    respondToWeather("unknown") // Outputs: Weather is unpredictable today.
}

In this example, the when expression checks the contents of the weather string to decide the response. The conditions use ignoreCase to handle variations in casing effectively.

Complex Conditions Inside when

You can leverage logical conditions to form more complex evaluations within the when statement.


val number = -10

when {
    number < 0 -> println("Negative number")
    number in 1..100 -> println("Positive number within range 1 to 100")
    number == 0 -> println("Zero")
    else -> println("Positive number greater than 100")
}

In this snippet, the when expression checks if the number is less than zero, within a specific range, equal to zero, or else comes to a logical conclusion.

Conclusion

Using when without an argument in Kotlin promotes clear and clean decision-making in code. It's a powerful part of the language that should certainly be part of every Kotlin developer's toolkit. Try out these examples, and you’ll soon appreciate the simplicity and readability when introduces to your code.

Next Article: Pattern Matching with `when` Expressions in Kotlin

Previous Article: Kotlin - Advanced `when` Expressions: Ranges, Types, and More

Series: Control Flow in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin