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...