Mobile Development
Kotlin
Subjective
Oct 04, 2025
Explain when expressions and how they differ from switch statements.
Detailed Explanation
When expressions are Kotlin's powerful replacement for Java's switch statements:\n\n1. Basic When Expression\n\nfun describe(x: Any) = when (x) {\n 1 -> "One"\n "Hello" -> "Greeting"\n is Long -> "Long number"\n !is String -> "Not a string"\n else -> "Unknown"\n}\n\n\n2. When as Statement vs Expression\n\n// As statement\nwhen (x) {\n 1 -> println("One")\n 2 -> println("Two")\n}\n\n// As expression (must be exhaustive)\nval result = when (x) {\n 1 -> "One"\n 2 -> "Two"\n else -> "Other"\n}\n\n\n3. Multiple Conditions\n\nwhen (x) {\n 0, 1 -> println("Small number")\n in 2..10 -> println("Medium number")\n in validNumbers -> println("Valid")\n !in 0..100 -> println("Out of range")\n}\n\n\n4. Smart Casting\n\nfun process(obj: Any) = when (obj) {\n is String -> obj.length // obj automatically cast to String\n is IntArray -> obj.sum() // obj automatically cast to IntArray\n is List<*> -> obj.size\n else -> 0\n}\n\n\n5. Exhaustive with Sealed Classes\n\nsealed class Result\nclass Success(val data: String) : Result()\nclass Error(val message: String) : Result()\n\nfun handle(result: Result) = when (result) {\n is Success -> "Data: ${result.data}"\n is Error -> "Error: ${result.message}"\n // No else needed - compiler ensures exhaustiveness\n}\n\n\n6. Capturing When Subject\n\nwhen (val trimmed = input?.trim()) {\n null -> println("Input is null")\n "" -> println("Input is empty")\n else -> println("Input: $trimmed")\n}\n\n\n7. Advantages over Switch\n• Returns values (expression)\n• Pattern matching with type checking\n• Smart casting\n• Range and collection checks\n• No fall-through (safer)\n• Exhaustiveness checking
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts