Bird
0
0

Which code correctly implements this?

hard📝 Application Q15 of 15
Kotlin - Control Flow as Expressions

You want to write a Kotlin when expression that prints "Weekend" if the day is either "Saturday" or "Sunday", "Weekday" if the day is any other day of the week, and "Invalid" for any other input. Which code correctly implements this?

Awhen(day) { in listOf("Saturday", "Sunday") -> println("Weekend") else -> println("Weekday") }
Bwhen(day) { "Saturday" || "Sunday" -> println("Weekend") else -> println("Weekday") }
Cwhen(day) { "Saturday", "Sunday" -> println("Weekend") "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> println("Weekday") else -> println("Invalid") }
Dwhen(day) { "Saturday" && "Sunday" -> println("Weekend") else -> println("Weekday") }
Step-by-Step Solution
Solution:
  1. Step 1: Check correct multiple condition syntax for weekend days

    when(day) { "Saturday", "Sunday" -> println("Weekend") "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> println("Weekday") else -> println("Invalid") } correctly uses commas to separate "Saturday" and "Sunday" to match either day.
  2. Step 2: Verify handling of other days and else case

    when(day) { "Saturday", "Sunday" -> println("Weekend") "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> println("Weekday") else -> println("Invalid") } lists all weekdays explicitly and uses else for invalid inputs, matching the problem requirements.
  3. Final Answer:

    when(day) { "Saturday", "Sunday" -> println("Weekend") "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> println("Weekday") else -> println("Invalid") } -> Option C
  4. Quick Check:

    Use commas for multiple matches and else for fallback [OK]
Quick Trick: List all matches with commas; use else for others [OK]
Common Mistakes:
MISTAKES
  • Using || or && instead of commas
  • Missing else for invalid inputs
  • Not listing all weekdays explicitly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes