The withIndex() extension function in Kotlin returns a lazy Iterable that wraps each element of the original set into an IndexedValue containing the index of that element and the element itself.
The syntax of Set.withIndex() extension function is:
fun <T> Set<T>.withIndex(): Iterable<IndexedValue<T>>
This withIndex() extension function of Set returns a lazy Iterable that wraps each element of the original set into an IndexedValue containing the index of that element and the element itself.
Set.withIndex() returns value of type Iterable
.
Using withIndex() to iterate over a set of integers with their indices.
For example,
fun main() {
val numbers = setOf(10, 20, 30)
for ((index, value) in numbers.withIndex()) {
println("Index: $index, Value: $value")
}
}
Index: 0, Value: 10 Index: 1, Value: 20 Index: 2, Value: 30
Using withIndex() to iterate over a set of strings with their indices.
For example,
fun main() {
val strings = setOf("apple", "banana", "cherry")
for ((index, value) in strings.withIndex()) {
println("Index: $index, Value: $value")
}
}
Index: 0, Value: apple Index: 1, Value: banana Index: 2, Value: cherry
Using withIndex() to iterate over a set of custom objects with their indices.
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))
for ((index, person) in people.withIndex()) {
println("Index: $index, Person: $person")
}
}
Index: 0, Person: Person(name=Alice, age=30) Index: 1, Person: Person(name=Bob, age=25) Index: 2, Person: Person(name=Charlie, age=35)
In this Kotlin tutorial, we learned about withIndex() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.