Reputation: 2117
Is this the idiomatic way to perform a short-circuiting search and map the result to a Boolean
?
val foos = mutableListOf<Foo>()
...
fun fooBar(bar: Bar) = if (null != foos.find { it.bar == bar }) true else false
Basically, I was looking for something along the lines of
fun Any?.exists() = null != this
fun fooBar(bar: Bar) = foos.find { it.bar == bar }.exists()
which seems like a useful pattern for anything that might return null
.
EDIT:
I settled on writing a simple extension function similar to filterIsInstance()
:
inline fun <reified R> Iterable<*>.findIsInstance(): R? {
for (element in this) if (element is R) return element
return null
}
Example usage:
val str = list.findIsInstance<String>() ?: return
Upvotes: 1
Views: 193