Bird
0
0

Which of the following is the correct syntax to use smart casts in a when expression for variable obj?

easy📝 Syntax Q12 of 15
Kotlin - Control Flow as Expressions
Which of the following is the correct syntax to use smart casts in a when expression for variable obj?
Awhen obj { is String -> println(obj.length) else -> println("Not a string") }
Bwhen (obj) { obj is String -> println(obj.length) else -> println("Not a string") }
Cwhen (obj) { String -> println(obj.length) else -> println("Not a string") }
Dwhen (obj) { is String -> println(obj.length) else -> println("Not a string") }
Step-by-Step Solution
Solution:
  1. Step 1: Check correct when syntax

    The when expression requires parentheses around the variable: when (obj).
  2. Step 2: Use type check correctly

    The correct type check is is String without repeating variable name inside the block.
  3. Final Answer:

    when (obj) { is String -> println(obj.length) else -> println("Not a string") } -> Option D
  4. Quick Check:

    Correct when syntax uses parentheses and is [OK]
Quick Trick: Use parentheses and 'is' keyword in when [OK]
Common Mistakes:
MISTAKES
  • Omitting parentheses around variable
  • Using variable name inside when branches
  • Using type name without 'is' keyword

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes