2023-05-03 11:06:20 +02:00
|
|
|
== Why is this an issue?
|
|
|
|
|
2022-11-29 10:56:55 +01:00
|
|
|
include::../description.adoc[]
|
|
|
|
|
2023-05-25 14:18:12 +02:00
|
|
|
=== Noncompliant code example
|
|
|
|
|
|
|
|
[source,kotlin]
|
|
|
|
----
|
|
|
|
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
|
|
|
|
----
|
|
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
|
|
|
|
[source,kotlin]
|
|
|
|
----
|
|
|
|
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
|
|
|
|
----
|
|
|
|
|