I’m looking into the std lib functions for Collect...
# announcements
j
I’m looking into the std lib functions for Collections, is there a function to get the first index of match to a predicate in the Iterable return null if not found? In other words, I want to avoid a double pass on the Collection by using
myCollection.indexOf(myCollection.find { predicate(it) })
(plus avoid the handling of
-1
as a result type.
For now we’re bundling this extension, but I wonder if the stdlib already provides a similar thing (I’d be happy to open a PR if not) https://dev.to/amay077/gets-first-index-of-match-to-condition-in-list-6c7
s
However, this function still returns
-1
if no element matches the predicate
j
Yes, correct. I’d like to avoid that extra hop, if possible. So, in the callsite, i’d like to be able to write
Copy code
val index: Int = myCollection.theMagicFunctionHere { myPredicate(it) } ?: somethingElse()
s
I dont think so. I made my own last time I needed it
d
that's very unusual thing: returning index as a null. Don't think kotlin will ever have it
why do you need non existing index be anything else other than -1?
s
You could use
takeIf { it != -1 }
to transform a
-1
to
null
Or create an extension function like:
Copy code
inline fun <T> Iterable<T>.indexOfFirstOrNull(predicate: (T) -> Boolean): Int? = indexOfFirst(predicate).takeIf { it != -1 }
👍 3
j
Thanks, yes that extension function would suffice, or the one I posted the link of as the second message of the thread. It seems like kotlin doesn’t provide it out of the box, and @Dias raises a good point re:predictability of the API as well.