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)