Kotlin Set elementAt()
Syntax & Examples


Set.elementAt() extension function

The elementAt() extension function for sets in Kotlin returns an element at the given index or throws an IndexOutOfBoundsException if the index is out of bounds of the set. Note that since sets are unordered, the order of elements is not guaranteed.


Syntax of Set.elementAt()

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

fun <T> Set<T>.elementAt(index: Int): T

This elementAt() extension function of Set returns an element at the given index or throws an IndexOutOfBoundsException if the index is out of bounds of this set.

Parameters

ParameterOptional/RequiredDescription
indexrequiredThe index of the element to return.

Return Type

Set.elementAt() returns value of type T.



✐ Examples

1 Using elementAt() to get an element at a specific index in a set

In Kotlin, we can use the elementAt() function to get an element at a specific index in a set of integers.

For example,

  1. Create a set of integers.
  2. Use the elementAt() function to get the element at index 2.
  3. Print the result to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val numbers = setOf(1, 2, 3, 4, 5)
    val element = numbers.elementAt(2)
    println("Element at index 2: $element")
}

Output

Element at index 2: 3

2 Using elementAt() with a set of strings

In Kotlin, we can use the elementAt() function to get an element at a specific index in a set of strings.

For example,

  1. Create a set of strings.
  2. Use the elementAt() function to get the element at index 1.
  3. Print the result to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val fruits = setOf("apple", "banana", "cherry", "date")
    val element = fruits.elementAt(1)
    println("Element at index 1: $element")
}

Output

Element at index 1: banana

3 Using elementAt() with an empty set

In Kotlin, using the elementAt() function on an empty set will throw an IndexOutOfBoundsException.

For example,

  1. Create an empty set of integers.
  2. Attempt to use the elementAt() function to get the element at index 0.
  3. Catch and handle the IndexOutOfBoundsException.
  4. Print an error message to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val emptySet = emptySet<Int>()
    try {
        val element = emptySet.elementAt(0)
        println("Element at index 0: $element")
    } catch (e: IndexOutOfBoundsException) {
        println("Error: ${e.message}")
    }
}

Output

Error: Index 0 out of bounds for length 0

Summary

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