Bird
0
0

You want to assign a grade based on a score using when as an expression. Which code correctly returns "A" for scores 90 and above, "B" for 80-89, "C" for 70-79, and "F" otherwise?

hard📝 Application Q15 of 15
Kotlin - Control Flow as Expressions
You want to assign a grade based on a score using when as an expression. Which code correctly returns "A" for scores 90 and above, "B" for 80-89, "C" for 70-79, and "F" otherwise?
Aval grade = when (score) { score >= 90 -> "A" score >= 80 -> "B" score >= 70 -> "C" else -> "F" }
Bval grade = when (score) { in 90..100 -> "A" in 80..89 -> "B" in 70..79 -> "C" else -> "F" }
Cval grade = when { score >= 90 -> "A" score >= 80 -> "B" score >= 70 -> "C" else -> "F" }
Dval grade = when { in 90..100 -> "A" in 80..89 -> "B" in 70..79 -> "C" else -> "F" }
Step-by-Step Solution
Solution:
  1. Step 1: Understand when with condition expressions

    val grade = when { score >= 90 -> "A" score >= 80 -> "B" score >= 70 -> "C" else -> "F" } uses when without argument and conditions like score >= 90, which is valid and clear for ranges.
  2. Step 2: Check other options for errors

    val grade = when (score) { in 90..100 -> "A" in 80..89 -> "B" in 70..79 -> "C" else -> "F" } is correct syntax but uses ranges; val grade = when (score) { score >= 90 -> "A" score >= 80 -> "B" score >= 70 -> "C" else -> "F" } incorrectly uses conditions inside when(score) which expects values, not conditions; val grade = when { in 90..100 -> "A" in 80..89 -> "B" in 70..79 -> "C" else -> "F" } uses in without variable, which is invalid.
  3. Final Answer:

    val grade = when { score >= 90 -> "A" score >= 80 -> "B" score >= 70 -> "C" else -> "F" } -> Option C
  4. Quick Check:

    Use when without argument for conditions [OK]
Quick Trick: Use when without argument for condition checks [OK]
Common Mistakes:
MISTAKES
  • Using conditions inside when(variable)
  • Omitting variable in range checks
  • Misplacing in keyword

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes