The filter(predicate) function is used to extract a subset of elements from a collection that match a given predicate. Many collection
functions such as any(), count(), first(), and more, come with an optional condition predicate.
It is not recommended to invoke the filter(predicate) function prior to these terminal operations. Instead, the predicate variant of
the terminal operation should be used as a replacement.
Using filter(predicate) before terminal operations can result in unnecessary iterations over the collection, which could negatively
impact the performance of the code, especially with large collections. By directly using the predicate variant of the function, you can streamline the
code and improve its efficiency and readability.
Replace the filter(predicate) call with the predicate variant of the terminal operation. As of Kotlin API version 1.8, the list of
terminal operations supporting a predicate is:
any() none() count() first(), firstOrNull() last(), lastOrNull() single(), singleOrNull()
val list = listOf(5,2,9,6,8,2,5,7,3)
val hasElementsGreater5 = list.filter { it > 5 }.any() // Noncompliant
val countElementsGreater5 = list.filter { it > 5 }.count() // Noncompliant
val lastElementGreater5 = list.filter { it > 5 }.lastOrNull() // Noncompliant
val list = listOf(5,2,9,6,8,2,5,7,3)
val hasElementsGreater5 = list.any { it > 5 } // Compliant
val countElementsGreater5 = list.count { it > 5 } // Compliant
val lastElementGreater5 = list.lastOrNull { it > 5 } // Compliant