Bird
0
0

Identify the error in this Kotlin code snippet:

medium📝 Debug Q14 of 15
Kotlin - Collections Fundamentals
Identify the error in this Kotlin code snippet:
val set = setOf(1, 2, 3)
set.add(4)
ARuntime error: UnsupportedOperationException when calling add()
BSyntax error: setOf cannot be used without mutable keyword
CCompile-time error: add() is not a function of Set
DNo error, set will contain 4 elements
Step-by-Step Solution
Solution:
  1. Step 1: Understand setOf creates immutable set

    The setOf() function returns an immutable set that does not support modification.
  2. Step 2: Analyze calling add() on immutable set

    Calling add() on a Set<T> causes a compile-time error because Set<T> has no add() method.
  3. Final Answer:

    Compile-time error: add() is not a function of Set -> Option C
  4. Quick Check:

    Immutable set + add() = compile error [OK]
Quick Trick: Immutable sets have no add() method: compile error [OK]
Common Mistakes:
MISTAKES
  • Expecting runtime error instead of compile-time error
  • Assuming setOf creates mutable sets
  • Thinking add() silently fails without error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes