Kotlin List.indexOf() – Examples

Kotlin List.indexOf()

The Kotlin List.indexOf() function returns the index (integer) of the first occurrence of the specified element in the list, or -1 if the specified element is not contained in the list.

Syntax

List.indexOf(element)

Example 1

In this example,

  1. Take a list of strings.
  2. Take a string. This is our element.
  3. Call indexOf() function on the list with the element passed as argument. Index of first occurrence of the element should be returned.

Program

fun main(args: Array<String>) {
    val list1 = listOf("a", "b", "v", "b", "m")
    val element = "b"
    val result = list1.indexOf(element)
    print(result)
}

Output

1

Example 2

In this example,

  1. Take a list of strings.
  2. Take a string. This is our element. Take a value for this element such that it is not present in the list.
  3. Call indexOf() function on the list with the element passed as argument. As element is not present, -1 should be returned.

Program

fun main(args: Array<String>) {
    val list1 = listOf("a", "b", "v", "b", "m")
    val element = "z"
    val result = list1.indexOf(element)
    print(result)
}

Output

-1