0
0
Kotlinprogramming~15 mins

When expression as powerful switch in Kotlin - Deep Dive

Choose your learning style9 modes available
Overview - When expression as powerful switch
What is it?
The 'when' expression in Kotlin is a way to choose between many options based on a value, similar to a switch statement in other languages. It lets you check a value against multiple conditions and run code depending on which condition matches. Unlike traditional switches, 'when' can be used as an expression that returns a value. It is more flexible and readable for handling multiple cases.
Why it matters
Without 'when', you would write many if-else statements that are harder to read and maintain. 'When' makes your code cleaner and easier to understand, especially when you have many choices to handle. It also reduces bugs by forcing you to cover all cases when used as an expression. This helps programmers write safer and more reliable code.
Where it fits
Before learning 'when', you should know basic Kotlin syntax and if-else statements. After mastering 'when', you can learn advanced pattern matching, sealed classes, and smart casting that work well with 'when' for more powerful code.
Mental Model
Core Idea
'When' is like a smart traffic controller that directs the program flow based on matching conditions, returning a result if needed.
Think of it like...
Imagine a restaurant waiter taking orders. Depending on what the customer says, the waiter brings the right dish. The 'when' expression listens to the input and chooses the correct action, just like the waiter choosing the dish.
┌───────────────┐
│   Input value │
└──────┬────────┘
       │
       ▼
┌─────────────────────────────┐
│          when expression     │
│ ┌─────────────┬───────────┐ │
│ │ Condition 1 │ Action 1  │ │
│ │ Condition 2 │ Action 2  │ │
│ │    ...      │   ...     │ │
│ │ Condition N │ Action N  │ │
│ └─────────────┴───────────┘ │
└───────────────┬─────────────┘
                │
                ▼
          Result or action
Build-Up - 7 Steps
1
FoundationBasic when syntax and usage
🤔
Concept: Learn the simplest form of 'when' to replace if-else chains.
In Kotlin, 'when' checks a value against multiple options. For example: val x = 2 when (x) { 1 -> println("One") 2 -> println("Two") else -> println("Other") } This prints 'Two' because x is 2.
Result
Output: Two
Understanding the basic syntax shows how 'when' simplifies multiple if-else checks into a clear, readable structure.
2
FoundationUsing when as an expression
🤔
Concept: 'When' can return a value, not just run code blocks.
You can assign the result of 'when' to a variable: val x = 3 val result = when (x) { 1 -> "One" 2 -> "Two" else -> "Unknown" } println(result) This prints 'Unknown' because x is 3.
Result
Output: Unknown
Knowing 'when' returns a value lets you write concise code without extra variables or statements.
3
IntermediateMultiple conditions and ranges
🤔Before reading on: do you think 'when' can check if a number is in a range like 1 to 5? Commit to your answer.
Concept: 'When' supports checking multiple values and ranges in one condition.
You can combine cases and use ranges: val x = 4 when (x) { 1, 2 -> println("One or Two") in 3..5 -> println("Between Three and Five") !in 6..10 -> println("Not between Six and Ten") else -> println("Other") } This prints 'Between Three and Five'.
Result
Output: Between Three and Five
Using ranges and multiple values in one case makes 'when' very powerful and expressive for many conditions.
4
IntermediateSmart casting with when
🤔Before reading on: do you think 'when' can automatically treat a variable as a specific type inside a branch? Commit to your answer.
Concept: 'When' works with Kotlin's smart casting to check types and use them safely.
Example: fun describe(obj: Any) = when (obj) { is String -> "String of length ${obj.length}" is Int -> "Integer value $obj" else -> "Unknown type" } println(describe("Hello")) println(describe(10)) Output: String of length 5 Integer value 10
Result
Output: String of length 5 Integer value 10
Smart casting inside 'when' branches avoids manual type checks and casts, making code safer and cleaner.
5
IntermediateUsing when without argument
🤔Before reading on: can 'when' be used without a value to check? Commit to your answer.
Concept: 'When' can be used like an if-else chain without a specific value to match.
Example: val x = 10 when { x % 2 == 0 -> println("Even") x % 2 != 0 -> println("Odd") } This prints 'Even' because 10 is divisible by 2.
Result
Output: Even
Using 'when' without an argument lets you write complex condition checks more clearly than nested if-else.
6
AdvancedExhaustive when with sealed classes
🤔Before reading on: do you think Kotlin forces you to cover all cases in 'when' when used as an expression? Commit to your answer.
Concept: When used with sealed classes, 'when' must cover all subclasses or use 'else', making code safer.
Example: sealed class Shape class Circle(val radius: Double) : Shape() class Rectangle(val width: Double, val height: Double) : Shape() fun area(shape: Shape) = when (shape) { is Circle -> Math.PI * shape.radius * shape.radius is Rectangle -> shape.width * shape.height } println(area(Circle(2.0))) println(area(Rectangle(3.0, 4.0))) If you miss a subclass, the compiler warns you.
Result
Output: 12.566370614359172 12.0
Exhaustive 'when' with sealed classes prevents missing cases, reducing runtime errors and improving code safety.
7
ExpertCompiler optimization and bytecode
🤔Before reading on: do you think 'when' compiles to a simple jump table like switch in Java? Commit to your answer.
Concept: 'When' compiles differently depending on cases: to jump tables, if-else chains, or method calls for maximum efficiency.
The Kotlin compiler analyzes 'when' cases: - For simple constants, it generates a Java switch (jump table). - For ranges or complex conditions, it uses if-else chains. - For sealed classes, it uses type checks and smart casts. This means 'when' is both expressive and performant.
Result
Output: No visible output, but efficient compiled code.
Understanding compilation helps write 'when' expressions that are both readable and optimized by the compiler.
Under the Hood
'When' works by evaluating the input value once, then checking each condition in order until one matches. If used as an expression, it returns the result of the matched branch. The Kotlin compiler translates 'when' into efficient bytecode: simple cases become switch statements, complex ones become if-else chains, and type checks use smart casting. This design balances flexibility and performance.
Why designed this way?
Kotlin's 'when' was designed to improve on Java's switch by supporting more types, ranges, and expressions. It unifies multiple conditional patterns into one construct, reducing boilerplate and errors. The compiler optimizes 'when' to avoid performance loss, making it practical for real-world use.
┌───────────────┐
│   Input value │
└──────┬────────┘
       │
       ▼
┌─────────────────────────────┐
│       Evaluate once          │
└──────┬──────────────────────┘
       │
       ▼
┌─────────────────────────────┐
│ Check condition 1 (constant) │───┐
│ Check condition 2 (range)    │   │
│ Check condition 3 (type)     │   │
│ ...                         │   │
└─────────────┬───────────────┘   │
              │                   │
              ▼                   │
       Match found?               │
         Yes │ No                │
              ▼                   │
      Execute branch              │
              │                   │
              ▼                   │
        Return result <───────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does 'when' always require an 'else' branch? Commit to yes or no.
Common Belief:Many think 'when' always needs an 'else' branch to cover all cases.
Tap to reveal reality
Reality:If 'when' is used as an expression and covers all possible cases (like with sealed classes), 'else' is not needed.
Why it matters:Adding unnecessary 'else' can hide missing cases, leading to bugs if new cases are added later.
Quick: Can 'when' only check simple values like integers? Commit to yes or no.
Common Belief:Some believe 'when' only works with simple constants like numbers or strings.
Tap to reveal reality
Reality:'When' can check complex conditions, ranges, types, and even be used without an argument for arbitrary boolean checks.
Why it matters:Limiting 'when' to simple values prevents using its full power and writing cleaner code.
Quick: Does 'when' always compile to a switch statement? Commit to yes or no.
Common Belief:People often think 'when' always compiles to a Java switch for performance.
Tap to reveal reality
Reality:It compiles to switch only for simple constant cases; otherwise, it uses if-else chains or type checks.
Why it matters:Knowing this helps write 'when' expressions that are both readable and performant.
Quick: Is 'when' just a fancy if-else with no real advantage? Commit to yes or no.
Common Belief:Some think 'when' is just syntactic sugar over if-else statements.
Tap to reveal reality
Reality:'When' is more powerful: it can be an expression, supports smart casting, multiple conditions, and compiler optimizations.
Why it matters:Underestimating 'when' leads to missing out on safer and more expressive code.
Expert Zone
1
'When' expressions with sealed classes enable exhaustive checks that the compiler enforces, preventing runtime errors.
2
Using 'when' without an argument allows combining multiple unrelated conditions elegantly, which is often overlooked.
3
The compiler's choice between switch and if-else for 'when' depends on the case types and count, affecting performance subtly.
When NOT to use
'When' is not ideal for very simple true/false checks where if-else is clearer. Also, for very large numbers of cases with complex logic, a map or polymorphism might be better alternatives.
Production Patterns
In production, 'when' is used for handling UI states, parsing inputs, and implementing state machines. Combined with sealed classes, it ensures all cases are handled, improving code safety and maintainability.
Connections
Pattern Matching (Functional Programming)
'When' builds on the idea of pattern matching by checking values and types to choose code paths.
Understanding 'when' helps grasp pattern matching concepts in languages like Scala or Haskell, which are more powerful but share the same core idea.
State Machines (Computer Science)
'When' expressions often implement state transitions by matching current states and inputs.
Knowing 'when' aids in designing clear and maintainable state machines, a fundamental concept in software design.
Decision Trees (Data Science)
'When' mimics decision trees by branching logic based on conditions to reach outcomes.
Recognizing this connection helps understand how branching logic in code relates to decision-making models in data science.
Common Pitfalls
#1Forgetting to cover all cases in 'when' used as an expression.
Wrong approach:val result = when (x) { 1 -> "One" 2 -> "Two" } // Missing else or other cases
Correct approach:val result = when (x) { 1 -> "One" 2 -> "Two" else -> "Other" }
Root cause:Not realizing that 'when' as an expression must be exhaustive to compile.
#2Using 'when' with complex conditions but forgetting to use 'when' without argument.
Wrong approach:when (x) { x % 2 == 0 -> println("Even") else -> println("Odd") }
Correct approach:when { x % 2 == 0 -> println("Even") else -> println("Odd") }
Root cause:Misunderstanding that 'when' with argument matches values, not boolean expressions.
#3Using 'else' branch unnecessarily with sealed classes.
Wrong approach:when (shape) { is Circle -> ... else -> ... // unnecessary else }
Correct approach:when (shape) { is Circle -> ... is Rectangle -> ... }
Root cause:Not knowing that sealed classes allow exhaustive 'when' without 'else'.
Key Takeaways
'When' in Kotlin is a powerful, flexible replacement for switch and if-else chains that can return values.
It supports multiple conditions, ranges, type checks, and can be used with or without an argument.
Using 'when' with sealed classes enables the compiler to enforce exhaustive checks, improving code safety.
The Kotlin compiler optimizes 'when' into efficient bytecode depending on the cases, balancing readability and performance.
Understanding 'when' unlocks clearer, safer, and more maintainable Kotlin code.