Kotlin List indexOf()
Syntax & Examples


Syntax of List.indexOf()

The syntax of List.indexOf() function is:

abstract fun indexOf(element: E): Int

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



✐ Examples

1 Example

In this example,

  • We create a list named list1 containing the elements 'a', 'b', 'c', 'd'.
  • We find the index of the first occurrence of 'a' using the List indexOf() function, which returns the index of the specified element.
  • The first occurrence of 'a' is at index 0 in list1, so indexA will be 0.
  • Finally, we print the value of indexA to standard output using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("a", "b", "c", "d")
    val indexA = list1.indexOf("a")
    println(indexA)
}

Output

0

2 Example

In this example,

  • We create a list named list1 containing the elements 10, 20, 30, 40.
  • We find the index of the first occurrence of 30 using the List indexOf() function, which returns the index of the specified element.
  • The first occurrence of 30 is at index 2 in list1, so index30 will be 2.
  • Finally, we print the value of index30 to standard output using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(10, 20, 30, 40)
    val index30 = list1.indexOf(30)
    println(index30)
}

Output

2

3 Example

In this example,

  • We create a list named list1 containing the elements 'apple', 'banana', 'cherry', 'date'.
  • We try to find the index of the first occurrence of 'grape' using the List indexOf() function, which returns the index of the specified element.
  • Since 'grape' is not present in list1, indexOf() returns -1.
  • Finally, we print the value of indexGrape to standard output using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("apple", "banana", "cherry", "date")
    val indexGrape = list1.indexOf("grape")
    println(indexGrape)
}

Output

-1

Summary

In this Kotlin tutorial, we learned about indexOf() function of List: the syntax and few working examples with output and detailed explanation for each example.