39 lines
1.1 KiB
Plaintext
Raw Permalink Normal View History

== Why is this an issue?
2023-06-29 14:07:20 +02:00
Passing a collection as an argument to the collection's own method is either an error - some other argument was intended - or simply nonsensical code.
2023-06-29 14:07:20 +02:00
Further, because some methods require that the argument remain unmodified during the execution, passing a collection to itself can result in undefined behavior.
2023-06-29 14:07:20 +02:00
== How to fix it
=== Code examples
==== Noncompliant code example
[source,kotlin,diff-id=1,diff-type=noncompliant]
----
val objs = mutableListOf<Any>()
objs.add("Hello")
objs.add(objs) // Noncompliant; StackOverflowException if objs.hashCode() called
objs.addAll(objs) // Noncompliant; behavior undefined
objs.containsAll(objs) // Noncompliant; always true
objs.removeAll(objs) // Noncompliant; confusing. Use clear() instead
objs.retainAll(objs) // Noncompliant; NOOP
----
2023-06-29 14:07:20 +02:00
==== Compliant solution
2023-06-29 14:07:20 +02:00
[source,kotlin,diff-id=1,diff-type=compliant]
----
val newList = mutableListOf<Any>()
val objs = mutableListOf<Any>()
objs.add("Hello")
objs.containsAll(newList) // Compliant
objs.addAll(newList) // Compliant
objs.removeAll(newList) // Compliant
objs.retainAll(newList) // Compliant
----