The onEachIndexed() extension function in Kotlin performs the given action on each element, providing the sequential index with the element, and returns the collection itself afterwards.
The syntax of Set.onEachIndexed() extension function is:
fun <T, C : Iterable<T>> C.onEachIndexed(action: (index: Int, T) -> Unit): C
This onEachIndexed() extension function of Set performs the given action on each element, providing sequential index with the element, and returns the collection itself afterwards.
Parameter | Optional/Required | Description |
---|---|---|
action | required | The action to be performed on each element, providing the sequential index. |
Set.onEachIndexed() returns value of type C
.
Using onEachIndexed() to print each element and its index in a set of integers.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
numbers.onEachIndexed { index, value -> println("Index: $index, Value: $value") }
println(numbers)
}
Index: 0, Value: 1 Index: 1, Value: 2 Index: 2, Value: 3 Index: 3, Value: 4 Index: 4, Value: 5 [1, 2, 3, 4, 5]
Using onEachIndexed() to print each element in uppercase and its index.
For example,
fun main() {
val strings = setOf("one", "two", "three")
strings.onEachIndexed { index, value -> println("Index: $index, Value: ${value.uppercase()}") }
println(strings)
}
Index: 0, Value: ONE Index: 1, Value: TWO Index: 2, Value: THREE [one, two, three]
Using onEachIndexed() to print the name of each custom object in a set along with its index.
For example,
data class Person(val name: String, val age: Int)
fun main() {
val people = setOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
people.onEachIndexed { index, person -> println("Index: $index, Name: ${person.name}") }
println(people)
}
Index: 0, Name: Alice Index: 1, Name: Bob Index: 2, Name: Charlie [Person(name=Alice, age=30), Person(name=Bob, age=25), Person(name=Charlie, age=35)]
In this Kotlin tutorial, we learned about onEachIndexed() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.