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. 🛡️
..

Post a Comment

Previous Post Next Post