Kotlin有array.indexOf,但我不知道如何做array.indexOfBy {lambda}

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

我在stdlib中缺少一个函数吗?

我可以用一个循环创建一个函数,当它找到目标时返回项目并返回。 喜欢这个:

 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 

有没有更优雅和习惯的方法来完成这个? 我也没有看到这样的列表,集合或序列的功能。

(这个问题来自另一篇文章的评论 )

你可以使用indexOfFirst

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

在某些情况下,方便的替代方案:

 a.indices.first { a[it] == 2 } // throws NoSuchElementException if not found a.indices.find { a[it] == 2 } // null if not found