IndexOf in Kotlin Arrays

How to 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?

+11
source share
2 answers

If you want to get the index of the maximum element, you can use the "maxBy" function:

 val maxIdx = nums.indices.maxBy { nums[it] } ?: -1 

This is more efficient since it will only move through the array once.

+12
source

With current Kotlin (1.0), you can use the indexOf() extension function on arrays:

 val x = arrayOf("happy","dancer","jumper").indexOf("dancer") 

All extension functions for arrays are in the api link .

In your example:

 val maxIdx = nums.indexOf(nums.max()) 
+3
source

All Articles