Bird
Raised Fist0
Kotlinprogramming~15 mins

When without argument in Kotlin - Deep Dive

Choose your learning style10 modes available
Overview - When without argument
What is it?
In Kotlin, the 'when' expression is a powerful tool for checking multiple conditions. When used without an argument, it acts like a series of if-else checks, evaluating each condition until one is true. This lets you write clear and concise code for complex decision-making without repeating the same variable. It is a flexible way to handle different cases based on boolean expressions.
Why it matters
Without 'when' expressions, you would often write long chains of if-else statements that can be hard to read and maintain. 'When' without an argument simplifies this by letting you list conditions clearly and cleanly. This improves code readability and reduces errors, making your programs easier to understand and change. Without it, your code might become cluttered and confusing, especially with many conditions.
Where it fits
Before learning 'when' without argument, you should understand basic if-else statements and expressions in Kotlin. After mastering this, you can explore 'when' with arguments, which matches values directly, and advanced control flow techniques like sealed classes and smart casts.
Mental Model
Core Idea
'When' without argument is like a clean, readable chain of if-else checks that stops at the first true condition.
Think of it like...
Imagine you are deciding what to wear based on the weather. Instead of asking 'Is it sunny?', then 'Is it raining?', you just check each condition one by one until one fits, then you pick your outfit. This is like 'when' without argument checking conditions in order.
┌───────────────────────────────┐
│          when {               │
│   condition1 -> action1       │
│   condition2 -> action2       │
│   condition3 -> action3       │
│   else -> defaultAction       │
└───────────────────────────────┘

Checks conditions top to bottom, runs first true action, skips rest.
Build-Up - 7 Steps
1
FoundationBasic if-else decision making
🤔
Concept: Understanding simple if-else statements as the foundation of conditional logic.
In Kotlin, you can use if-else to choose between actions: val number = 10 if (number > 0) { println("Positive") } else { println("Not positive") }
Result
Prints: Positive
Knowing how if-else works is essential because 'when' without argument is a cleaner way to write multiple if-else checks.
2
FoundationIntroduction to 'when' expression
🤔
Concept: 'When' can replace multiple if-else statements for checking a value.
Using 'when' with an argument: val x = 2 when (x) { 1 -> println("One") 2 -> println("Two") else -> println("Other") }
Result
Prints: Two
Understanding 'when' with argument shows how Kotlin simplifies multiple checks on the same value.
3
Intermediate'When' without argument syntax
🤔
Concept: 'When' can be used without an argument to check boolean conditions directly.
Example: val a = 5 val b = 10 when { a > b -> println("a is greater") a == b -> println("a equals b") else -> println("a is smaller") }
Result
Prints: a is smaller
Knowing that 'when' without argument evaluates conditions in order helps write clearer decision logic.
4
IntermediateMultiple conditions in 'when' branches
🤔Before reading on: Do you think you can combine multiple conditions in one 'when' branch using commas? Commit to your answer.
Concept: You can combine multiple conditions in one branch separated by commas to run the same action.
Example: val x = 3 when { x == 1, x == 2 -> println("One or Two") x == 3 -> println("Three") else -> println("Other") }
Result
Prints: Three
Understanding combined conditions reduces code duplication and makes 'when' branches more concise.
5
IntermediateUsing 'else' as a fallback branch
🤔
Concept: 'Else' branch runs if no other condition matches, ensuring all cases are handled.
Example: val y = 0 when { y > 0 -> println("Positive") y < 0 -> println("Negative") else -> println("Zero") }
Result
Prints: Zero
Knowing to always include 'else' prevents missing cases and runtime errors.
6
AdvancedReturning values from 'when' without argument
🤔Before reading on: Do you think 'when' without argument can return a value like an expression? Commit to your answer.
Concept: 'When' without argument can be used as an expression that returns a value based on conditions.
Example: val score = 85 val grade = when { score >= 90 -> "A" score >= 80 -> "B" score >= 70 -> "C" else -> "F" } println(grade)
Result
Prints: B
Understanding 'when' as an expression unlocks concise, readable value assignments based on conditions.
7
ExpertShort-circuiting and evaluation order in 'when'
🤔Before reading on: Does 'when' evaluate all conditions or stop at the first true one? Commit to your answer.
Concept: 'When' evaluates conditions top to bottom and stops at the first true condition, skipping the rest.
Example: fun check(): Boolean { println("Checking condition") return true } when { check() -> println("First true") else -> println("Fallback") } Only 'check()' is called once, then 'First true' prints.
Result
Prints: Checking condition First true
Knowing evaluation stops early helps avoid unnecessary work and side effects in conditions.
Under the Hood
'When' without argument works by evaluating each condition as a boolean expression in order. Internally, Kotlin compiles this into a series of if-else checks. Once a condition evaluates to true, it executes the corresponding branch and skips the rest. If none match, the 'else' branch runs if present. This makes 'when' a control flow structure that efficiently handles multiple boolean conditions.
Why designed this way?
Kotlin designed 'when' without argument to improve readability and reduce boilerplate compared to long if-else chains. It provides a clear syntax for multiple conditions without repeating the variable or expression. This design balances expressiveness and simplicity, avoiding complex pattern matching syntax while supporting flexible condition checks.
┌───────────────┐
│   when {      │
│ ┌───────────┐ │
│ │ cond1?    │─┬─> execute branch1
│ └───────────┘ │
│       │ false │
│ ┌───────────┐ │
│ │ cond2?    │─┬─> execute branch2
│ └───────────┘ │
│       │ false │
│      ...       │
│       │       │
│   else branch │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does 'when' without argument evaluate all conditions or stop at the first true one? Commit to your answer.
Common Belief:Some think 'when' checks all conditions even after finding a true one.
Tap to reveal reality
Reality:'When' stops evaluating conditions as soon as it finds the first true condition.
Why it matters:Believing all conditions run can lead to inefficient code or unexpected side effects if conditions have function calls.
Quick: Can 'when' without argument be used without an 'else' branch safely? Commit to your answer.
Common Belief:Many assume 'else' is optional and missing it is fine if all cases seem covered.
Tap to reveal reality
Reality:If no condition matches and 'else' is missing, Kotlin throws a runtime exception.
Why it matters:Missing 'else' can cause crashes in production if unexpected inputs occur.
Quick: Does 'when' without argument require all conditions to be boolean expressions? Commit to your answer.
Common Belief:Some believe you can use non-boolean expressions as conditions in 'when' without argument.
Tap to reveal reality
Reality:Conditions must be boolean expressions; otherwise, the code won't compile.
Why it matters:Misunderstanding this causes compilation errors and confusion about how 'when' works.
Quick: Can 'when' without argument be used to match values directly like 'when' with argument? Commit to your answer.
Common Belief:Some think 'when' without argument can match values directly like 'when' with argument.
Tap to reveal reality
Reality:'When' without argument only evaluates boolean conditions, not direct value matches.
Why it matters:Confusing these leads to incorrect code and misunderstanding of control flow.
Expert Zone
1
Conditions in 'when' without argument can include complex expressions, including function calls and logical operators, but side effects must be managed carefully.
2
The Kotlin compiler optimizes 'when' without argument into efficient bytecode similar to if-else chains, but understanding this helps in performance-critical code.
3
Using 'when' without argument inside inline functions or lambdas can affect inlining and performance, a subtlety often overlooked.
When NOT to use
'When' without argument is not suitable when you want to match a single value against constants or types; use 'when' with argument instead. Also, for very simple true/false checks, a simple if-else might be clearer.
Production Patterns
In production, 'when' without argument is often used for complex validation logic, feature toggles, or multi-condition routing where conditions are boolean expressions. It helps keep code readable and maintainable compared to nested if-else.
Connections
If-Else Statements
'When' without argument builds on and replaces long if-else chains.
Understanding if-else deeply helps grasp how 'when' simplifies multiple condition checks.
Pattern Matching (Functional Programming)
'When' with argument is similar to pattern matching; 'when' without argument extends this to boolean conditions.
Knowing pattern matching concepts clarifies the design and power of Kotlin's 'when' expression.
Decision Trees (Data Science)
'When' without argument resembles decision trees where conditions are checked in order to decide outcomes.
Seeing 'when' as a decision tree helps understand its evaluation order and short-circuiting behavior.
Common Pitfalls
#1Omitting the 'else' branch and assuming all cases are covered.
Wrong approach:when { x > 0 -> println("Positive") x < 0 -> println("Negative") } // No else branch
Correct approach:when { x > 0 -> println("Positive") x < 0 -> println("Negative") else -> println("Zero or unknown") }
Root cause:Not realizing that 'when' requires an 'else' to handle unmatched cases to avoid runtime exceptions.
#2Using non-boolean expressions as conditions in 'when' without argument.
Wrong approach:when { 5 -> println("Five") else -> println("Other") }
Correct approach:when { x == 5 -> println("Five") else -> println("Other") }
Root cause:Misunderstanding that conditions must be boolean expressions, not values.
#3Expecting all conditions to run instead of stopping at the first true one.
Wrong approach:when { expensiveCheck1() -> println("First") expensiveCheck2() -> println("Second") else -> println("None") }
Correct approach:when { expensiveCheck1() -> println("First") expensiveCheck2() -> println("Second") else -> println("None") } // But understand only first true condition runs
Root cause:Not knowing 'when' short-circuits evaluation, leading to unexpected side effects or performance issues.
Key Takeaways
'When' without argument in Kotlin is a clean way to write multiple boolean condition checks, acting like a chain of if-else statements.
It evaluates conditions from top to bottom and stops at the first true condition, improving efficiency and clarity.
Always include an 'else' branch to handle unexpected cases and avoid runtime errors.
'When' without argument can be used as an expression to return values based on conditions, making code concise and readable.
Understanding this construct helps write clearer, safer, and more maintainable Kotlin code for complex decision logic.

Practice

(1/5)
1. What does when without argument do in Kotlin?
easy
A. It matches a value against constants only.
B. It checks boolean conditions one by one until one is true.
C. It creates a loop that runs multiple times.
D. It declares a variable with multiple types.

Solution

  1. Step 1: Understand when without argument

    When used without an argument, when evaluates each condition as a boolean expression.
  2. Step 2: Compare with other uses

    Unlike when with argument, it does not match values but checks conditions one by one.
  3. Final Answer:

    It checks boolean conditions one by one until one is true. -> Option B
  4. Quick Check:

    when without argument = boolean checks [OK]
Hint: Remember: no argument means boolean conditions checked [OK]
Common Mistakes:
  • Thinking it matches values like switch-case
  • Confusing it with loops
  • Assuming it declares variables
2. Which of the following is the correct syntax for when without argument in Kotlin?
easy
A. when { condition1 -> action1 condition2 -> action2 else -> defaultAction }
B. when(value) { 1 -> action1 2 -> action2 else -> defaultAction }
C. when (condition) { true -> action1 false -> action2 }
D. when (value) { condition1 -> action1 condition2 -> action2 }

Solution

  1. Step 1: Identify when without argument syntax

    The correct syntax omits the argument and uses boolean conditions directly inside curly braces.
  2. Step 2: Check options

    when { condition1 -> action1 condition2 -> action2 else -> defaultAction } matches this pattern with conditions and an else branch; others use an argument or incorrect structure.
  3. Final Answer:

    when { condition1 -> action1 condition2 -> action2 else -> defaultAction } -> Option A
  4. Quick Check:

    Correct syntax = when { condition1 -> action1 condition2 -> action2 else -> defaultAction } [OK]
Hint: No argument means conditions directly inside braces [OK]
Common Mistakes:
  • Adding argument inside parentheses
  • Missing else branch
  • Using values instead of conditions
3. What is the output of this Kotlin code?
val x = 10
when {
  x < 5 -> println("Less than 5")
  x in 5..10 -> println("Between 5 and 10")
  else -> println("More than 10")
}
medium
A. More than 10
B. Less than 5
C. Between 5 and 10
D. No output

Solution

  1. Step 1: Evaluate conditions in order

    First condition: x < 5 is false (10 < 5 is false). Second condition: x in 5..10 is true (10 is in 5 to 10).
  2. Step 2: Execute matching branch

    Since second condition is true, it prints "Between 5 and 10" and stops checking further.
  3. Final Answer:

    Between 5 and 10 -> Option C
  4. Quick Check:

    10 in 5..10 = true [OK]
Hint: Check conditions top to bottom, first true runs [OK]
Common Mistakes:
  • Assuming x < 5 is true
  • Ignoring range check
  • Expecting else branch output
4. Find the error in this Kotlin code using when without argument:
val y = 3
val result = when {
  y > 5 -> println("Greater than 5")
  y < 5 -> println("Less than 5")
}
medium
A. Missing else branch for unmatched cases
B. Incorrect use of parentheses after when
C. Conditions must be constants, not expressions
D. Cannot use println inside when

Solution

  1. Step 1: Check when branches

    The code has two conditions but no else branch to handle all other cases.
  2. Step 2: Understand Kotlin requirement

    When used without argument, Kotlin requires an else branch to cover all possibilities or the compiler errors about non-exhaustive when.
  3. Final Answer:

    Missing else branch for unmatched cases -> Option A
  4. Quick Check:

    Always add else branch [OK]
Hint: Always include else branch in when without argument [OK]
Common Mistakes:
  • Ignoring else branch requirement
  • Adding parentheses after when
  • Thinking conditions must be constants
5. You want to print a message based on temperature:
val temp = 25
when {
  temp <= 0 -> println("Freezing")
  temp in 1..15 -> println("Cold")
  temp in 16..25 -> println("Warm")
  temp > 25 -> println("Hot")
  else -> println("Unknown")
}

What will be printed and why is this when usage correct?
hard
A. Compilation error due to overlapping ranges
B. "Cold"; because 25 is in 1..15 range
C. "Hot"; because 25 is greater than 25
D. "Warm"; because conditions cover all ranges with else as fallback

Solution

  1. Step 1: Check which condition matches temp = 25

    temp <= 0 is false; temp in 1..15 is false; temp in 16..25 is true (25 is included).
  2. Step 2: Confirm correctness of when usage

    All possible values are covered by conditions and else branch ensures fallback; no overlap causes error.
  3. Final Answer:

    "Warm"; because conditions cover all ranges with else as fallback -> Option D
  4. Quick Check:

    25 in 16..25 = true, else covers all [OK]
Hint: Check ranges carefully; else handles unexpected values [OK]
Common Mistakes:
  • Misreading range boundaries
  • Assuming 25 > 25 is true
  • Thinking else is optional
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard