Quick Answer

Functional-style collection operations

Understanding the Issue

Kotlin provides filter and filterNot functions to select elements from collections based on predicates. These return new collections containing only matching elements.

The Problem

This code demonstrates the issue:

Kotlin Error
// Problem: Imperative filtering
val evens = mutableListOf<Int>()
for (n in numbers) {
    if (n % 2 == 0) {
        evens.add(n)
    }
}

The Solution

Here's the corrected code:

Kotlin Fixed
// Solution: Functional filtering
val evens = numbers.filter { it % 2 == 0 }

// Filtering maps:
val adults = people.filter { (name, age) -> age >= 18 }

// FilterNot variant:
val nonEmpty = strings.filterNot { it.isEmpty() }

Key Takeaways

Prefer functional filtering operations for more expressive collection processing.