Kotlin Tutorials

Kotlin Set elementAtOrNull()
Syntax & Examples

Set.elementAtOrNull() extension function

The elementAtOrNull() extension function for sets in Kotlin returns an element at the given index or null if the index is out of bounds of the set.


Syntax of Set.elementAtOrNull()

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

fun <T> Set<T>.elementAtOrNull(index: Int): T?

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

Parameters

ParameterOptional/RequiredDescription
indexrequiredThe index of the element to return.

Return Type

Set.elementAtOrNull() returns value of type T?.



✐ Examples

1 Using elementAtOrNull() to get an element at a specific index or null

In Kotlin, we can use the elementAtOrNull() function to get an element at a specific index in a set of integers or return null if the index is out of bounds.

For example,

  1. Create a set of integers.
  2. Use the elementAtOrNull() 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.elementAtOrNull(2)
    println("Element at index 2: $element")
}

Output

Element at index 2: 3

2 Using elementAtOrNull() with a set of strings

In Kotlin, we can use the elementAtOrNull() function to get an element at a specific index in a set of strings or return null if the index is out of bounds.

For example,

  1. Create a set of strings.
  2. Use the elementAtOrNull() function to get the element at index 5.
  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.elementAtOrNull(5)
    println("Element at index 5: $element")
}

Output

Element at index 5: null

3 Using elementAtOrNull() with an empty set

In Kotlin, we can use the elementAtOrNull() function on an empty set to return null if the index is out of bounds.

For example,

  1. Create an empty set of integers.
  2. Use the elementAtOrNull() function to get the element at index 0.
  3. Print the result to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val emptySet = emptySet<Int>()
    val element = emptySet.elementAtOrNull(0)
    println("Element at index 0 in empty set: $element")
}

Output

Element at index 0 in empty set: null

Summary

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