First On Possibly Empty (ARCH8078)
Ce contenu n’est pas encore disponible dans votre langue.
Key kotlin.performance.first-on-possibly-empty · Severity warning · Category performance
Flags first() / last() / [0] on a filtered or fetched collection with no emptiness guard - NoSuchElementException on the empty case.
Incorrect
Section titled “Incorrect”val u = users.filter { it.active }.first()Correct
Section titled “Correct”val u = users.firstOrNull { it.active } ?: returnUse firstOrNull / lastOrNull / getOrNull and handle null.