Kotlin Set withIndex()
Syntax & Examples
Set.withIndex() extension function
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.
Syntax of Set.withIndex()
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.
Return Type
Set.withIndex() returns value of type Iterable
.
✐ Examples
1 Using withIndex with a set of integers
Using withIndex() to iterate over a set of integers with their indices.
For example,
- Create a set of integers.
- Use withIndex() to wrap each element with its index.
- Iterate over the resulting Iterable and print each IndexedValue.
Kotlin Program
fun main() {
val numbers = setOf(10, 20, 30)
for ((index, value) in numbers.withIndex()) {
println("Index: $index, Value: $value")
}
}
Output
Index: 0, Value: 10 Index: 1, Value: 20 Index: 2, Value: 30
2 Using withIndex with a set of strings
Using withIndex() to iterate over a set of strings with their indices.
For example,
- Create a set of strings.
- Use withIndex() to wrap each element with its index.
- Iterate over the resulting Iterable and print each IndexedValue.
Kotlin Program
fun main() {
val strings = setOf("apple", "banana", "cherry")
for ((index, value) in strings.withIndex()) {
println("Index: $index, Value: $value")
}
}
Output
Index: 0, Value: apple Index: 1, Value: banana Index: 2, Value: cherry
3 Using withIndex with a set of custom objects
Using withIndex() to iterate over a set of custom objects with their indices.
For example,
- Create a data class.
- Create a set of custom objects.
- Use withIndex() to wrap each element with its index.
- Iterate over the resulting Iterable and print each IndexedValue.
Kotlin Program
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")
}
}
Output
Index: 0, Person: Person(name=Alice, age=30) Index: 1, Person: Person(name=Bob, age=25) Index: 2, Person: Person(name=Charlie, age=35)
Summary
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.