Which of the following Kotlin code snippets correctly uses if as an expression?
easy📝 Syntax Q3 of 15
Kotlin - Control Flow as Expressions
Which of the following Kotlin code snippets correctly uses if as an expression?
Aval result = if (score > 50) "Pass" else "Fail"
Bval result = if score > 50 then "Pass" else "Fail"
Cval result = if (score > 50) { "Pass" }
Dval result = if (score > 50) "Pass"
Step-by-Step Solution
Solution:
Step 1: Check syntax correctness
val result = if (score > 50) "Pass" else "Fail" uses correct Kotlin syntax with parentheses and else branch.
Step 2: Identify errors in other options
val result = if score > 50 then "Pass" else "Fail" uses invalid keywords 'then'. val result = if (score > 50) { "Pass" } misses else branch. val result = if (score > 50) "Pass" misses else branch too.
Final Answer:
val result = if (score > 50) "Pass" else "Fail" -> Option A
Quick Check:
If expression needs else branch for assignment [OK]
Quick Trick:Always include else when using if as expression [OK]
Common Mistakes:
MISTAKES
Using 'then' keyword (not Kotlin)
Omitting else branch in if expression
Missing parentheses around condition
Master "Control Flow as Expressions" in Kotlin
9 interactive learning modes - each teaches the same concept differently