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.
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.
Parameter | Optional/Required | Description |
---|---|---|
index | required | The index of the element to return. |
Set.elementAtOrNull() returns value of type T?
.
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,
elementAtOrNull()
function to get the element at index 2.println
function.fun main(args: Array<String>) {
val numbers = setOf(1, 2, 3, 4, 5)
val element = numbers.elementAtOrNull(2)
println("Element at index 2: $element")
}
Element at index 2: 3
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,
elementAtOrNull()
function to get the element at index 5.println
function.fun main(args: Array<String>) {
val fruits = setOf("apple", "banana", "cherry", "date")
val element = fruits.elementAtOrNull(5)
println("Element at index 5: $element")
}
Element at index 5: null
In Kotlin, we can use the elementAtOrNull()
function on an empty set to return null if the index is out of bounds.
For example,
elementAtOrNull()
function to get the element at index 0.println
function.fun main(args: Array<String>) {
val emptySet = emptySet<Int>()
val element = emptySet.elementAtOrNull(0)
println("Element at index 0 in empty set: $element")
}
Element at index 0 in empty set: null
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.