Find family

Say you have an unordered list of objects:

data class Person(val firstName: String, 
val lastName: String,
val age: Int)
val people = listOf(Person("Jane", "Doe", 19),
Person("John", "Doe", 24),
Person("John", "Smith", 23))

And would like to find a first object that matches some criteria. Using extension functions, you could write something like this:

fun <T> List<T>.find(check: (T) -> Boolean): T? {
for (p in this) {
if (check(p)) {
return p
}
}
return null
}

And then, when you have a list of objects, you can simply call find() on it:

println(people.find {
it.firstName == "John"
}) // Person(firstName=John, lastName=Doe)

Luckily, you don't have to implement anything. This method is already implemented for you in Kotlin.

There's also an accompanying findLast() method, which does the same, but which starts with the last element of the collection:

println(people.findLast {
it.firstName == "John"
}) // Person(firstName=John, lastName=Smith)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.34.226