Bird
0
0

What will be the output of this Kotlin code?

medium📝 Predict Output Q13 of 15
Kotlin - Collections Fundamentals
What will be the output of this Kotlin code?
val numbers = mutableSetOf(1, 2, 3)
numbers.add(2)
numbers.add(4)
println(numbers)
ACompilation error
B[1, 2, 3, 2, 4]
C[1, 2, 3]
D[1, 2, 3, 4]
Step-by-Step Solution
Solution:
  1. Step 1: Understand mutableSetOf and add behavior

    The set starts with 1, 2, 3. Adding 2 again does nothing because sets ignore duplicates. Adding 4 adds a new element.
  2. Step 2: Determine final set contents

    After additions, the set contains 1, 2, 3, and 4.
  3. Final Answer:

    [1, 2, 3, 4] -> Option D
  4. Quick Check:

    Sets ignore duplicates, so 2 is not added twice [OK]
Quick Trick: Adding duplicates to sets does nothing [OK]
Common Mistakes:
MISTAKES
  • Expecting duplicates to appear in output
  • Confusing set print format with list
  • Thinking add returns error on duplicates

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes