Is there a more Kotlin-like alternative to express...
# announcements
e
Is there a more Kotlin-like alternative to express this piece of code?
Copy code
var n = completionProviders.indexOfFirst(...) + 1

if (n == 0) {
  n = completionProviders.size
}
Not with takeUnless/takeIf
r
Not sure it’s any better, but I’d be tempted by this:
Copy code
inline fun <T> List<T>.indexOfFirstOrNull(predicate: (T) -> Boolean): Int? {
    val indexOfFirst = indexOfFirst(predicate)
    return if (indexOfFirst >= 0) indexOfFirst else null
}

completionProviders
    .indexOfFirstOrNull { it == ... }
    ?.let { it + 1 }
    ?: completionProviders.size
n
Why no takeIf? Seems like the natural continuation
👍🏻 1
☝️ 1
Would be good to know the reason otherwise other offered solutions might have the same issue
Copy code
val n = completionProviders.indexOfFirst(...).let { if (it == -1) completionProviders.size else it + 1 }
I like Rob's solution as well, never really understood or liked the -1 convention in a language with built in null handling
e
boxed integer :(
e
@Nir I don't like those two functions with primitive data types, that's all 😆
n
Some kind of performance thing I guess?
e
@Rob Elliot thanks! But doesn't it seem like overcomplicating the thing?
@Nir no, just one of my rules/preferences
@Nir but yeah. It doesn't make sense to allow wrapper classes here, as it would happen with takeIf
e
maybe inline classes someday
n
@Edoardo Luppi I have to admit then I just don't understand outside of performance reasons what the motivation is
Perf wise hard for me to comment, it's not an ultra high perf language, so worrying about microoptimizations seems suboptimal
e
@Nir a clear distinction of applicability for extension functions