Kotlin Tutorials

Kotlin Set indexOf()
Syntax & Examples

Set.indexOf() extension function

The indexOf() extension function in Kotlin returns the first index of the specified element, or -1 if the set does not contain the element.


Syntax of Set.indexOf()

The syntax of Set.indexOf() extension function is:

fun <T> Set<T>.indexOf(element: T): Int

This indexOf() extension function of Set returns first index of element, or -1 if the collection does not contain element.

Parameters

ParameterOptional/RequiredDescription
elementrequiredThe element to search for in the set.

Return Type

Set.indexOf() returns value of type Int.



✐ Examples

1 Finding the index of an element

Using indexOf() to find the index of an element in a set.

For example,

  1. Create a set of integers.
  2. Use indexOf() to find the index of a specific element in the set.
  3. Print the resulting index.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3, 4, 5)
    val index = numbers.indexOf(3)
    println(index)
}

Output

2

2 Finding the index of a non-existent element

Using indexOf() to find the index of a non-existent element in a set.

For example,

  1. Create a set of integers.
  2. Use indexOf() to find the index of an element that is not in the set.
  3. Print the resulting index, which should be -1.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3, 4, 5)
    val index = numbers.indexOf(6)
    println(index)
}

Output

-1

3 Finding the index of a string in a set

Using indexOf() to find the index of a string in a set of strings.

For example,

  1. Create a set of strings.
  2. Use indexOf() to find the index of a specific string in the set.
  3. Print the resulting index.

Kotlin Program

fun main() {
    val strings = setOf("a", "b", "c")
    val index = strings.indexOf("b")
    println(index)
}

Output

1

Summary

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