indexOf in Kotlin Arrays

Viewed 18044

How do I get the index of a value from a Kotlin array?

My best solution right now is using:

val max = nums.max()
val maxIdx = nums.indices.find({ (i) -> nums[i] == max }) ?: -1

is there a better way?

3 Answers

If you want to find the item based on some predicate, then you can use indexOfFirst and indexOfLast extension functions.

val strings = arrayOf("hello","world","hello")
val firstHelloIndex = strings.indexOfFirst { it == "hello" }
val lastHelloIndex  = strings.indexOfLast  { it == "hello" }
Related