Problem Statement
How do you use when expressions in Kotlin for different types of conditions and pattern matching?
Explanation
Use when with an argument to match against specific values like when open paren x close paren open curly 1 arrow print first, 2 comma 3 arrow print second or third, in 4 dot dot 10 arrow print in range close curly, supporting multiple values with commas, ranges with in, type checks with is, and arbitrary expressions. When without an argument works like if-else chains allowing any boolean conditions like when open curly x greater 0 arrow print positive, x less 0 arrow print negative, else arrow print zero close curly.
When is an expression returning the value of the matched branch, so you can assign it to variables or return it from functions, but then it must be exhaustive covering all cases or including else. Use when for type-based dispatching with is checks getting automatic smart casts in the branches, sealed class hierarchies for compile-time exhaustiveness checking, and complex conditional logic that would be ugly with nested if-else.
When is more powerful and flexible than Java's switch, supporting rich pattern matching and making code more declarative and readable. It's one of Kotlin's most versatile control flow constructs combining the benefits of switch, if-else, and pattern matching.
