KOTLIN TIP #5

COLLECTION FILTERING

Collections are dealt with quite often when working with an API. More often then not, you want to filter or modify the contents of that collection. By using Kotlin’s collection filtering, adding clarity and making your code more succinct. It’s easier to tell what your resulting list should contain with collection filtering like the following:

val users = api.getUsers()
// we only want to show the active users in one list
val activeUsersNames = items.filter {
    it.active // the "it" variable is the parameter for single parameter lamdba functions
}
adapter.setUsers(activeUsers)

Filtering a collection using the built-in Kotlin methods is very comparable to other functional programming languages too, such as Java 8 streams or Swift collection types. Being able to filter collections in a unified way helps when talking with team members about what operations need to be done to get a list down to the right elements to display.

Leave a comment