Kotlin Array.indexOf()

Kotlin Array.indexOf() function

In Kotlin, the Array.indexOf() function is used to find the index of the first occurrence of a specified element in the array. If the element is not found, it returns -1.

In this tutorial, we’ll explore the syntax of the Array.indexOf() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the Array.indexOf() function is as follows:

fun <T> Array<out T>.indexOf(element: T): Int

where

ParameterDescription
elementThe element to search for in the array.
Parameters of Array indexOf() function

The indexOf() function returns the index of the first occurrence of the specified element in the array as an Int.

Examples for Array.indexOf() function

1. Finding the Index of an Element

In this example, we’ll use indexOf() function to find the index of a specific element "mango" in the given array of strings fruitsArray.

Kotlin Program

fun main() {
    val fruitsArray = arrayOf("apple", "banana", "kiwi", "mango", "banana")

    // Finding the index of the first occurrence of "mango"
    val mangoIndex = fruitsArray.indexOf("mango")

    // Printing the original array and the result
    println("Fruits Array\n${fruitsArray.contentToString()}\n")
    println("Index of 'mango'\n$mangoIndex")
}

Output

Fruits Array
[apple, banana, kiwi, mango, banana]

Index of 'mango'
3

2. Finding the Index of an Element that is not present in the Array

In this example, we’ll handle the scenario where the element we are trying to find the index of, is not present in the Array.

Kotlin Program

fun main() {
    val fruitsArray = arrayOf("apple", "banana", "kiwi", "mango", "banana")

    // Finding the index of the first occurrence of "orange"
    val orangeIndex = fruitsArray.indexOf("orange")

    // Printing the original array and the result
    println("Fruits Array\n${fruitsArray.contentToString()}\n")
    println("Index of 'banana'\n$orangeIndex")
}

Output

Fruits Array
[apple, banana, kiwi, mango, banana]

Index of 'banana'
-1

Summary

In this tutorial, we’ve covered the indexOf() function in Kotlin arrays, its syntax, and how to use it to find the index of the first occurrence of a specified element. Remember that the function returns -1 if the element is not found.