Which do you prefer? :one: `for (index in 0 until...
# codingconventions
m
Which do you prefer? 1️⃣
for (index in 0 until itemCount) {
2️⃣
repeat(itemCount) { index ->
1️⃣ 3
2️⃣ 31
a
I’d say it depends on the use case, if the index represents something like a position I would use 1, but if it’s only used as the current iteration of the loop I would use 2
j
Yes, I'd say it depends on what you want to express. Use
repeat
if you want to repeat something multiple times. Use
forEach
or
forEachIndexed
if you want to iterate a collection. I rarely ever use explicit
for
loops
m
I should probably have mentioned that, here, an
index
refers to an item index in a list (but we do not have direct access to that list, otherwise we would just use
forEachIndexed
)
j
Could you please share a bit more about how you use that loop, then?
m
Any API that accepts a position (in a list) as a function arg. For example,
getItemId
in
RecyclerView.Adapter
In my particular case (not using that exact function) I have:
Copy code
for (position in 0 until itemCount) {
    val item = itemAtPosition(position)
    if (item is Foo) {
        notifyItemChanged(position)
    }
}
e
if it's over a list, I would definitely write
Copy code
for (index in list.indices) {
(unless
for ((index, elem) in list.withIndex()) {
works better in context, of course)
m
Ok, but in this case there is no direct access to the list
j
Kind of related: turns out collection operators create a lot of garbage (gc) if used often, e.g. in render loops like jetpack compose where regular for loops will not. Most of the time you'd want to prioritize readability though.
they only make sense on
RandomAccess
lists which aren't being mutated, which should be most lists, but it's hard to guarantee unless you are in control of the data (and Compose only uses those helpers on its own data)
j
Exactly
m
Also if you need to use
continue
in your loop body, you can't use
repeat
.