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.
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.
Parameter | Optional/Required | Description |
---|---|---|
index | required | The index of the element to return. |
Set.elementAt() returns value of type T
.
In Kotlin, we can use the elementAt()
function to get an element at a specific index in a set of integers.
For example,
elementAt()
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.elementAt(2)
println("Element at index 2: $element")
}
Element at index 2: 3
In Kotlin, we can use the elementAt()
function to get an element at a specific index in a set of strings.
For example,
elementAt()
function to get the element at index 1.println
function.fun main(args: Array<String>) {
val fruits = setOf("apple", "banana", "cherry", "date")
val element = fruits.elementAt(1)
println("Element at index 1: $element")
}
Element at index 1: banana
In Kotlin, using the elementAt()
function on an empty set will throw an IndexOutOfBoundsException.
For example,
elementAt()
function to get the element at index 0.println
function.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}")
}
}
Error: Index 0 out of bounds for length 0
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.