What if you never had to count items manually in a loop again?
Why For loop with index (withIndex) in Kotlin? - Purpose & Use Cases
Imagine you have a list of customer names and you want to print each name with its position number. Doing this manually means counting each item yourself or writing extra code to track the position.
Manually keeping track of the index is slow and easy to mess up. You might forget to increase the count or mix up the numbers, causing confusion and errors in your output.
The withIndex() function in Kotlin lets you loop through items and get their index automatically. This means you don't have to count or track positions yourself, making your code cleaner and less error-prone.
var index = 0 for (item in list) { println("${index}: $item") index++ }
for ((index, item) in list.withIndex()) { println("${index}: $item") }
You can easily access both the position and value of items in a list, making tasks like numbering, labeling, or referencing much simpler.
When showing a list of orders on a screen, you can display each order with its number automatically, so customers see "0. Order A", "1. Order B", and so on, without extra counting code.
Manually tracking indexes is error-prone and tedious.
withIndex() automates index tracking in loops.
This makes your code cleaner, safer, and easier to read.