Kotlin when Expression Explained (2025 Guide to Smarter Conditional Logic)

Kotlin When Expression: Streamline Your Code in 2025! ๐Ÿš€

Replace clunky if..else chains with Kotlin’s when expression for cleaner, more readable conditional logic! ๐ŸŒŸ It’s a powerful, flexible tool that selects a code path based on conditions, acting like a modernized switch with superpowers. ๐ŸŽ‰

  • ๐Ÿ” Basic When: Match values for simple branching. ✅
  • ๐Ÿ“Š When as Expression: Return values directly. ๐Ÿ“ฆ
  • ⚖️ Advanced Features: Ranges, type checks, and more. ๐ŸŒˆ

Basic When Expression ๐Ÿ”

The when expression matches a value against branches, executing the first matching block. It’s Kotlin’s sleek alternative to Java’s switch! ๐ŸŒŸ


fun main() {
    val day = 4 // ๐Ÿ”ข Day number
    val result = when (day) { // ๐ŸŒŸ Match day
        1 -> "Monday" // ๐Ÿ“…
        2 -> "Tuesday"
        3 -> "Wednesday"
        4 -> "Thursday"
        5 -> "Friday"
        6 -> "Saturday"
        7 -> "Sunday"
        else -> "Invalid day." // ๐Ÿšซ Fallback
    }
    println(result) // Outputs: Thursday ๐Ÿ“Š
}

How It Works:

  • ๐Ÿ” Single Check: The input (day) is evaluated once. ⚖️
  • ➡️ Arrow Syntax: -> links conditions to results. ๐Ÿ“Œ
  • Match and Run: Executes the matching branch. ๐Ÿš€
  • ๐Ÿšซ else: Handles unmatched cases, required for expressions. ๐Ÿ“ฆ

When as an Expression ๐Ÿ“ฆ

Like if, when can return a value when assigned to a variable, making it ultra-concise! ๐ŸŽฏ Use else to ensure all cases are covered.


fun main() {
    val x: Any = 13.37 // ๐Ÿ”ข Any type
    val result = when (x) { // ๐ŸŒŸ Type checking
        is Int -> "is an Int" // ✅ Int match
        !is Double -> "is not Double" // ❌ Not Double
        is String -> "is a String" // ๐Ÿ“œ String match
        else -> "is none of the above" // ๐Ÿšซ Fallback
    }
    println("$x $result") // Outputs: 13.37 is none of the above ✨
}

Expression Benefits:

  • ๐Ÿ“ฆ Return Value: Assigns results directly to variables. ✅
  • Compact: Replaces verbose conditionals. ๐Ÿงน
  • ๐Ÿ” Versatile: Handles types, values, and conditions. ๐ŸŒˆ

Advanced When Features: Ranges, Multiple Values, and More ๐Ÿ’ก

The when expression shines with advanced capabilities like ranges, multiple value matching, and type checks. ๐ŸŒŸ

  • ๐Ÿ“‹ Multiple Values: Match multiple options (e.g., 1, 2, 3). ๐Ÿ”ข
  • ๐Ÿ“ Ranges: Use in or !in for ranges (e.g., in 1..10). ๐Ÿ“Š
  • ๐Ÿ”Ž Type Checks: Use is or !is for type matching. ๐Ÿงฉ
  • Condition Blocks: Evaluate complex conditions without an argument. ๐Ÿง 

fun main() {
    val month = 3 // ๐Ÿ”ข Month number
    when (month) { // ๐ŸŒŸ Match with ranges
        1, 2, 3 -> println("Spring ๐ŸŒธ") // ๐Ÿ“‹ Multiple values
        in 4..6 -> println("Summer ☀️") // ๐Ÿ“ Range
        in 7..9 -> println("Fall ๐Ÿ‚")
        in 10..12 -> println("Winter ❄️")
        else -> println("Invalid Month ๐Ÿšซ")
    } // Outputs: Spring ๐ŸŒธ ๐Ÿ“Š

    val value: Any = "Kotlin" // ๐Ÿ”ข Any type
    when (value) { // ๐ŸŒŸ Type checking
        is String -> println("String of length ${value.length}") // ๐Ÿ“œ
        is Int -> println("Integer: $value")
        else -> println("Unknown type")
    } // Outputs: String of length 6 ๐Ÿ“Š
}

Advanced Tip: Combine ranges and type checks for powerful, readable logic! ๐Ÿš€

When Without an Argument ๐Ÿง 

Use when without an argument to evaluate arbitrary conditions, replacing complex if-else ladders. ⚖️


fun main() {
    val score = 85 // ๐Ÿ”ข Student score
    val grade = when { // ๐ŸŒŸ No argument
        score >= 90 -> "A" // ๐Ÿฅ‡
        score >= 80 -> "B" // ๐Ÿฅˆ
        score >= 70 -> "C" // ๐Ÿฅ‰
        else -> "D" // ๐Ÿ“‰
    }
    println("Grade: $grade") // Outputs: Grade: B ๐Ÿ“Š
}

No-Argument Benefit: Simplifies condition-heavy logic into a clean, expressive format. ๐Ÿงน

When with Null Safety ๐Ÿšจ

Kotlin’s null safety integrates seamlessly with when to handle nullable types safely. ๐Ÿ›ก️


fun main() {
    val name: String? = null // ๐ŸŒˆ Nullable string
    when (name) { // ๐Ÿ” Check for null
        null -> println("Name is null") // ๐Ÿšซ
        else -> println("Name: $name, Length: ${name.length}") // ✅
    } // Outputs: Name is null ๐Ÿ“Š
}

Null Safety Tip: Use when with null checks or combine with ?. and ?: for robust handling. ⚡

Provided Example: If vs. When ๐Ÿ“

The provided code compares if and when, showcasing when’s elegance. Here’s an enhanced version with detailed comments:


fun main() {
    // ๐Ÿ› ️ If Statements
    var age = 17 // ๐Ÿ”ข Age input
    if (age >= 21) { // ๐ŸŒŸ Check drinking age
        print("Now you may drink in the US ๐Ÿบ") // ๐Ÿฅ‚
    } else if (age >= 18) { // ๐Ÿ” Check voting age
        print("Now you may vote ๐Ÿ—ณ️") // ๐Ÿ—ณ️
    } else if (age >= 16) { // ๐Ÿ” Check driving age
        print("You now may drive ๐Ÿš—") // ๐Ÿš—
    } else { // ๐Ÿ›‘ Fallback
        print("You're too young ๐Ÿ‘ถ") // ๐Ÿ‘ถ
    } // Outputs: You now may drive ๐Ÿš— ๐Ÿ“Š

    // ๐ŸŒˆ When Expression
    var season = 3 // ๐Ÿ”ข Season number
    when (season) { // ๐Ÿ“… Match season
        1 -> println("Spring ๐ŸŒธ")
        2 -> println("Summer ☀️")
        3 -> println("Fall ๐Ÿ‚")
        4 -> println("Winter ❄️")
        else -> println("Invalid Season ๐Ÿšซ")
    } // Outputs: Fall ๐Ÿ‚ ๐Ÿ“Š

    // ๐Ÿ“ When with ranges
    var month = 3 // ๐Ÿ”ข Month number
    when (month) { // ๐ŸŒŸ Match with ranges
        1, 2, 3 -> println("Spring ๐ŸŒธ") // ๐Ÿ“‹ Multiple values
        in 4..6 -> println("Summer ☀️") // ๐Ÿ“ Range
        in 7..9 -> println("Fall ๐Ÿ‚")
        in 10..12 -> println("Winter ❄️")
        else -> println("Invalid Month ๐Ÿšซ")
    } // Outputs: Spring ๐ŸŒธ ๐Ÿ“Š

    // ๐ŸŽฏ If-to-When Challenge
    when (age) { // ๐ŸŒŸ Convert if to when
        !in 0..20 -> print("Now you may drink in the US ๐Ÿบ") // ๐Ÿฅ‚
        in 18..20 -> print("Now you may vote ๐Ÿ—ณ️") // ๐Ÿ—ณ️
        16, 17 -> print("You now may drive ๐Ÿš—") // ๐Ÿš—
        else -> print("You're too young ๐Ÿ‘ถ") // ๐Ÿ‘ถ
    } // Outputs: You now may drive ๐Ÿš— ๐Ÿ“Š
}

Comparison Insight: when is more concise and readable for value matching or range checks compared to if. ⚖️

Practical Use Case: Menu System ๐Ÿฝ️

Use when to build a user-friendly menu system for apps or scripts. ๐Ÿ› ️


fun main() {
    val choice = 2 // ๐Ÿ”ข User menu selection
    val action = when (choice) { // ๐ŸŒŸ Match menu option
        1 -> "Start Game ๐ŸŽฎ"
        2 -> "View Scores ๐Ÿ†"
        3 -> "Settings ⚙️"
        4 -> "Exit ๐Ÿšช"
        else -> "Invalid Option ๐Ÿšซ"
    }
    println(action) // Outputs: View Scores ๐Ÿ† ๐Ÿ“Š
}

Menu Tip: Combine when with user input for interactive, dynamic systems. ๐ŸŽฏ

when vs. if vs. Java switch ⚖️

Compare when with if and Java’s switch to choose the right tool. ๐Ÿ“Š


fun main() {
    val code = 2 // ๐Ÿ”ข Input code
    // Using if
    val ifResult = if (code == 1) "Low" else if (code == 2) "Medium" else "High"
    // Using when
    val whenResult = when (code) { // ๐ŸŒŸ Cleaner
        1 -> "Low"
        2 -> "Medium"
        else -> "High"
    }
    println("if: $ifResult") // Outputs: if: Medium ๐Ÿ“Š
    println("when: $whenResult") // Outputs: when: Medium ๐Ÿ“Š
}
  • ๐Ÿ” when: Best for value matching, ranges, or type checks. ๐ŸŒˆ
  • ๐Ÿ› ️ if: Ideal for complex or nested conditions. ๐Ÿงฉ
  • ๐Ÿšซ Java switch: Less flexible, no ranges or type checks, requires break. ๐Ÿ“œ

Comparison Tip: Use when for clean, multi-branch logic; reserve if for intricate conditions. ⚖️

Best Practices for When Expressions ✅

  • ๐Ÿงน Keep It Simple: Use when for value matching or ranges to avoid clutter. ๐ŸŒˆ
  • Include else: Ensure all cases are covered when assigning to variables. ๐Ÿšซ
  • ๐Ÿ“ Use Ranges: Leverage in and !in for numeric or enum ranges. ๐Ÿ”ข
  • ๐Ÿ”Ž Type Safety: Use is for type checks with smart casts. ๐Ÿงฉ
  • ๐Ÿ›ก️ Null Handling: Check for null explicitly in when branches. ๐Ÿšจ
  • ๐Ÿ“ Readable Code: Add comments for complex when logic to aid maintenance. ๐Ÿง 

Frequently Asked Questions (FAQ) ❓

  • Why use when instead of if? ๐Ÿค”
    when is more concise for value matching, ranges, or type checks, reducing boilerplate compared to if-else ladders. ๐ŸŒˆ
  • Is else mandatory in when expressions? ๐Ÿšซ
    Yes, when assigning when to a variable to ensure all paths return a value; optional otherwise. ๐Ÿ“ฆ
  • Can when handle ranges and types? ๐Ÿ“Š
    Yes, use in for ranges (e.g., in 1..10) and is for type checks (e.g., is String). ๐Ÿ”Ž
  • How does when differ from Java’s switch? ⚖️
    when supports ranges, type checks, and expressions, doesn’t need break, and is more flexible than switch. ๐Ÿ“œ
  • Can when be used without an argument? ๐Ÿง 
    Yes, when without an argument evaluates conditions like if-else, ideal for complex logic. ⚡
  • How does when handle nulls? ๐Ÿšจ
    Check null explicitly in a branch or use null-safe operators (?., ?:) for nullable inputs. ๐Ÿ›ก️
..

Comments

Popular posts from this blog

Creating Beautiful Card UI in Flutter

Master Web Development with Web School Offline

Jetpack Compose - Card View