EntangledLoops
EntangledLoops

Reputation: 2117

Idiomatic way to map single object

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

Answers (1)

user
user

Reputation: 7604

I believe you are looking for any, which returns true if any of the elements match the given predicate, and is short-circuiting

fun fooBar(bar: Bar) = foos.any { it.bar == bar }

Upvotes: 4

Related Questions