The elementAtOrElse() extension function for sets in Kotlin returns an element at the given index or the result of calling the defaultValue function if the index is out of bounds of the set.
The syntax of Set.elementAtOrElse() extension function is:
fun <T> Set<T>.elementAtOrElse(index: Int, defaultValue: (Int) -> T): T
This elementAtOrElse() extension function of Set returns an element at the given index or the result of calling the defaultValue function if the index is out of bounds of this set.
Parameter | Optional/Required | Description |
---|---|---|
index | required | The index of the element to return. |
defaultValue | required | A function that takes an out-of-bounds index and returns a default value. |
Set.elementAtOrElse() returns value of type T
.
In Kotlin, we can use the elementAtOrElse()
function to get an element at a specific index in a set of integers or return a default value if the index is out of bounds.
For example,
elementAtOrElse()
function to get the element at index 2 or return -1 if the index is out of bounds.println
function.fun main(args: Array<String>) {
val numbers = setOf(1, 2, 3, 4, 5)
val element = numbers.elementAtOrElse(2) { -1 }
println("Element at index 2: $element")
}
Element at index 2: 3
In Kotlin, we can use the elementAtOrElse()
function to get an element at a specific index in a set of strings or return a default value if the index is out of bounds.
For example,
elementAtOrElse()
function to get the element at index 5 or return "unknown" if the index is out of bounds.println
function.fun main(args: Array<String>) {
val fruits = setOf("apple", "banana", "cherry", "date")
val element = fruits.elementAtOrElse(5) { "unknown" }
println("Element at index 5: $element")
}
Element at index 5: unknown
In Kotlin, we can use the elementAtOrElse()
function on an empty set to return a default value if the index is out of bounds.
For example,
elementAtOrElse()
function to get the element at index 0 or return -1 if the index is out of bounds.println
function.fun main(args: Array<String>) {
val emptySet = emptySet<Int>()
val element = emptySet.elementAtOrElse(0) { -1 }
println("Element at index 0 in empty set: $element")
}
Element at index 0 in empty set: -1
In this Kotlin tutorial, we learned about elementAtOrElse() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.