Bird
0
0

You want to write a Kotlin when expression that returns:

hard📝 Application Q15 of 15
Kotlin - Control Flow as Expressions
You want to write a Kotlin when expression that returns:
- "Small Int" if the value is an Int between 1 and 10 inclusive,
- "Large Int" if the value is an Int greater than 10,
- "String" if the value is a String,
- "Other" for anything else.

Which of the following when expressions correctly implements this?
Awhen (v) { in 1..10 -> "Small Int" is Int -> "Large Int" is String -> "String" else -> "Other" }
Bwhen (v) { is Int -> if (v in 1..10) "Small Int" else "Large Int" is String -> "String" else -> "Other" }
Cwhen (v) { is Int in 1..10 -> "Small Int" is Int -> "Large Int" is String -> "String" else -> "Other" }
Dwhen (v) { is Int && v in 1..10 -> "Small Int" is Int -> "Large Int" is String -> "String" else -> "Other" }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the conditions needed

    We need to check if v is an Int and then check its value range for "Small Int" or "Large Int". Also check if v is a String.
  2. Step 2: Analyze each option's correctness

    when (v) { in 1..10 -> "Small Int" is Int -> "Large Int" is String -> "String" else -> "Other" } incorrectly uses in 1..10 without checking type first, causing errors if v is not Int. when (v) { is Int in 1..10 -> "Small Int" is Int -> "Large Int" is String -> "String" else -> "Other" } uses invalid syntax is Int in 1..10. when (v) { is Int && v in 1..10 -> "Small Int" is Int -> "Large Int" is String -> "String" else -> "Other" } uses invalid syntax is Int && v in 1..10 inside when. when (v) { is Int -> if (v in 1..10) "Small Int" else "Large Int" is String -> "String" else -> "Other" } correctly checks type first, then uses an if inside the branch to distinguish ranges.
  3. Final Answer:

    Option B correctly implements the logic. -> Option B
  4. Quick Check:

    Use nested if inside when for complex conditions [OK]
Quick Trick: Check type first, then range inside branch with if [OK]
Common Mistakes:
MISTAKES
  • Using invalid syntax combining is and in
  • Not checking type before range
  • Trying to use logical operators directly in when cases

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes