Kotlin

Lesson 05

Collection transformations

Prefer collection operations that name the data rule instead of manual mutable accumulation.

Good Code

src/main/kotlin/reviews/ReviewQueries.kt
fun approvedTitles(reviews: List<Review>): List<String> {
    // The pipeline names the approval rule before selecting titles.
    return reviews
        .filter { review -> review.score >= 4 }
        .map { review -> review.title }
}

Bad Code

ReviewQueries.kt
fun approvedTitles(reviews: List<Review>): List<String> {
    val titles = mutableListOf<String>()
    for (review in reviews) {
        // Mutation hides the selection rule inside loop plumbing.
        titles.add(review.title)
    }
    return titles
}

Review Notes

What to review

Good Code

The good version puts the approval rule next to the transformation, so the output list follows from the pipeline.

Bad Code

The bad version builds a mutable list and forgets the score check, making the loop mechanics louder than the domain rule.

Takeaways

  • Kotlin collection review should connect filter, map, and mapNotNull to the domain rule being applied.