June 2018
Intermediate to advanced
310 pages
6h 32m
English
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 ...
Read now
Unlock full access