gpt4 book ai didi

Kotlin 有 array.indexOf 但我无法弄清楚如何做 array.indexOfBy { lambda }

转载 作者:IT老高 更新时间:2023-10-28 13:46:31 25 4
gpt4 key购买 nike

Kotlin 有 array.indexOf(item) 但我不知道如何做 array.indexOfBy { lambda }。它不存在吗?我可以find 一个项目,但我不能同时获得它的索引。

我是否缺少标准库中的函数?

我可以创建一个带有循环的函数,该循环检查项目并在找到目标时返回。像这样:

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
}

然后我尝试使用 forEach 使其功能更强大:

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

或者我可以做一些像这样但性能不是很好的愚蠢的事情:

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

有没有更优雅和惯用的方法来完成这个?!?对于列表、集合或序列,我也看不到这样的函数。

(本题来源于comment on another post)

最佳答案

您可以使用 indexOfFirst

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

关于Kotlin 有 array.indexOf 但我无法弄清楚如何做 array.indexOfBy { lambda },我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35759172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com