https://kotlinlang.org logo
Title
d

dierre

03/06/2018, 9:23 AM
Hello, I found an annoying behaviour here (https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/first.html), if the array is empty it is thrown a
NoSuchElementException
. I found that I can obtain what I want using filter and then checking against list size. I was expecting to return a `T?`(meaning an optional of some kind) instead of
T
. So basically instead of doing
list.first({p -> predicate}).orElse(defaultObject)
I have to do something like
var result = list.filter({p -> predicate}); if(result.isEmpty()) return defaultObject else result.first()
. Do you think there is a better approach?
s

spand

03/06/2018, 9:26 AM
Use
firstOrNull()
instead of
first()
ie.
list.firstOrNull { pred(it) } ?: defaultObject
d

dierre

03/06/2018, 9:28 AM
tnx!