When Expression in Kotlin Programming language

0

 

When Expression in Kotlin Programming language

Understanding the when Expression in Kotlin

The when expression is one of Kotlin's most flexible control structures, enabling you to handle multiple conditions efficiently and readably. This lecture covers all aspects of when, with examples and syntax details.

  • 1. When Expression Basics
  • 2. when with Multiple Branches
  • 3. Using when as an Expression
  • 4. when with Ranges
  • 5. when with Types
  • 6. Block Syntax in when
  • 7. Function Calling in when Block
  • 8. Passing Arguments in when Expression

1. When Expression Basics

The when expression in Kotlin functions like a switch statement in other languages, but with more powerful capabilities. It allows matching values, ranges, types, and even function calls.


// Basic when expression
fun main() {
    val number = 3

    when (number) {
        1 -> println("One")
        2 -> println("Two")
        3 -> println("Three") // Output: Three
        else -> println("Unknown number")
    }
}

2. when with Multiple Branches

Multiple branches can be combined within the same condition using commas.


// Using multiple branches in when
fun main() {
    val day = "Sunday"

    when (day) {
        "Saturday", "Sunday" -> println("It's the weekend!")
        else -> println("It's a weekday.")
    }
}

3. Using when as an Expression

In Kotlin, when can return values, which makes it a true expression. This is especially useful for assigning values based on conditions.


// Using when as an expression
fun main() {
    val number = 2

    val result = when (number) {
        1 -> "One"
        2 -> "Two"
        else -> "Unknown"
    }

    println("Result: $result") // Output: Result: Two
}

4. when with Ranges

The when expression supports ranges, which allows checking if a value falls within a specific range. Note: If you don't know about ranges, check the ranges lecture here: Ranges in Kotlin.


// when with ranges
fun main() {
    val age = 18

    when (age) {
        in 0..12 -> println("Child")
        in 13..19 -> println("Teenager")
        in 20..64 -> println("Adult")
        else -> println("Senior")
    }
}

5. when with Types

Using when with types allows you to handle conditions based on the type of a variable. This is helpful in functions that accept Any type arguments.


// when with type checking
fun printType(input: Any) {
    when (input) {
        is Int -> println("It's an integer.")
        is String -> println("It's a string with length ${input.length}.")
        is Boolean -> println("It's a boolean value.")
        else -> println("Unknown type.")
    }
}

fun main() {
    printType(42)
    printType("Kotlin")
    printType(true)
}

6. Block Syntax in when Expression

To execute multiple statements within a when case, use braces { } for block syntax.


// when with block syntax
fun main() {
    val command = "start"

    when (command) {
        "start" -> {
            println("Starting system...")
            println("System started successfully.")
        }
        "stop" -> {
            println("Stopping system...")
            println("System stopped.")
        }
        else -> {
            println("Unknown command")
        }
    }
}

7. Function Calling in when Block

You can call functions directly within each branch of a when expression, which is helpful for cleaner code.


// when with function calling
fun startSystem() = println("System started.")
fun stopSystem() = println("System stopped.")

fun main() {
    val action = "start"

    when (action) {
        "start" -> startSystem()
        "stop" -> stopSystem()
        else -> println("Unknown action")
    }
}

8. Passing Arguments in when Expression

Arguments can be passed into functions within a when expression to handle more complex conditions.


// when with function calls and arguments
fun greetPerson(name: String) = println("Hello, $name!")

fun main() {
    val user = "Alice"

    when (user) {
        "Alice" -> greetPerson(user)
        "Bob" -> greetPerson(user)
        else -> println("User not recognized")
    }
}

Difference Between if-else and when Expressions

The if-else statement is useful for straightforward true/false conditions, while the when expression is optimal for matching multiple cases, checking ranges, types, or values within a cleaner structure.



Simple Project: Menu Selection with when


// Simple menu-based application using when
fun showMenu(option: Int) {
    when (option) {
        1 -> println("1 for Insert User")
        2 -> println("2 for Check User")
        3 -> println("3 for Edit User")
        4 -> println("4 for Delete User")
        5 -> println("5 for Exit")
        else -> println("Invalid selection. Please try again.")
    }
}

fun main() {
    val userChoice = 2
    showMenu(userChoice)
}

Post a Comment

0Comments

Post a Comment (0)