Kotlin 有array.indexOf(item)个,但我不知道怎么做array.indexOfBy { lambda }个.它不存在吗?我可以同时获取一个项目,但无法同时获取其索引.

我在stdlib中丢失了一个函数吗?

I can create a function with a loop that chekcs the items and returns when it finds the target. Like this:

fun <T : Any> indexOfBy(items: Array<T>, predicate: (T) -> Boolean): Int {
    for (i in items.indices) { // or (i in 0..items.size-1)
        if (predicate(items[i])) {
            return i
        }
    }
    return -1
}

然后我try 使用forEach使其更具功能性:

fun <T : Any> indexOfBy(items: Array<T>, predicate: (T) -> Boolean): Int {
    (items.indices).forEach {
        if (predicate(items[it])) {
            return it
        }
    }
    return -1
}

Or I can do something silly like this which isn't very performant:

val slowAndSilly = people.indexOf(people.find { it.name == "David" })

看起来最好的可能是扩展函数:

fun <T: Any> Array<T>.indexOfBy(predicate: (T)->Boolean): Int =
        this.withIndex().find { predicate(it.value) }?.index ?: -1
fun <T: Any> Collection<T>.indexOfBy(predicate: (T)->Boolean): Int =
        this.withIndex().find { predicate(it.value) }?.index ?: -1
fun <T: Any> Sequence<T>.indexOfBy(predicate: (T)->Boolean): Int =
        this.withIndex().find { predicate(it.value) }?.index ?: -1

Is there a more elegant and idiomatic way to accomplish this?!? I also don't see a function like this for lists, collections nor sequences.

(this question is derived from the 100)

推荐答案

你可以用indexOfFirst

arrayOf(1, 2, 3).indexOfFirst { it == 2 } // returns 1
arrayOf(4, 5, 6).indexOfFirst { it < 3 } // returns -1

Kotlin相关问答推荐

导入org.gradle.jvm.toolchain.internal.JavaToolchainFactory未解析引用:Java工具链工厂

Kotlin Poet 的导入不明确

Mockk:对同一函数进行两次存根会忽略第一个行为

Kotlin中用于调用常量名称的枚举类方法之间的区别

Kotlin 函数中接收者和参数的类型相同

高效匹配两个 Flux

JavaFX - 你如何在 Kotlin 中使用 MapValueFactory?

is return inside function definition 也是 kotlin 中的表达式

Kotlin - 创建指定长度的随机整数的 ArrayList?

@InlineOnly 注释是什么意思?

如何在 Kotlin 文件中的 Android Studio 中控制何时将 Imports 替换为通配符

Kotlin 创建snackbar

ActivityOptions.makeSceneTransitionAnimation 在具有多个视图的 kotlin 中不起作用

防止导航到同一个片段

Kotlin:什么是 kotlin.String!类型

用Gradle Kotlin DSL构建源jar?

不推荐使用仅限生命周期的LifecycleEvent

如何限制kotlin协程的最大并发性

Kotlin 中内部可见性修饰符的范围

Kotlin类型安全类型别名