Bird
0
0

You have a list of user names and want to print how many users are online only if the list is not empty. Which Kotlin code snippet correctly does this?

hard📝 Application Q15 of 15
Kotlin - Collections Fundamentals
You have a list of user names and want to print how many users are online only if the list is not empty. Which Kotlin code snippet correctly does this?
Aif (users.isEmpty()) println("Online users: ${users.size}")
Bif (users.size > 0) println("Online users: ${users.size}")
Cif (users.count == 0) println("Online users: ${users.count}")
Dif (users.isNotEmpty) println("Online users: ${users.size}")
Step-by-Step Solution
Solution:
  1. Step 1: Check condition for non-empty list

    Using users.size > 0 correctly checks if the list has one or more elements.
  2. Step 2: Verify printing statement

    The print statement uses string interpolation to show the number of users online.
  3. Step 3: Analyze incorrect options

    isEmpty() checks for empty, so if (users.isEmpty()) println("Online users: ${users.size}") prints when empty, which is wrong.
    count is a function, so count == 0 is invalid.
    isNotEmpty without parentheses is incorrect syntax.
  4. Final Answer:

    if (users.size > 0) println("Online users: ${users.size}") -> Option B
  5. Quick Check:

    Check size > 0 for non-empty list [OK]
Quick Trick: Use size > 0 or isNotEmpty() with parentheses [OK]
Common Mistakes:
MISTAKES
  • Using isEmpty() to check for non-empty
  • Calling count without parentheses
  • Omitting parentheses on isNotEmpty()

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes