https://kotlinlang.org logo
Title
m

Mark

04/09/2023, 4:01 AM
Which do you prefer? 1️⃣
for (index in 0 until itemCount) {
2️⃣
repeat(itemCount) { index ->
a

asdf asdf

04/09/2023, 4:32 AM
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

Joffrey

04/09/2023, 7:07 AM
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

Mark

04/09/2023, 9:06 AM
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

Joffrey

04/09/2023, 9:21 AM
Could you please share a bit more about how you use that loop, then?
m

Mark

04/09/2023, 9:36 AM
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:
for (position in 0 until itemCount) {
    val item = itemAtPosition(position)
    if (item is Foo) {
        notifyItemChanged(position)
    }
}
e

ephemient

04/11/2023, 6:51 AM
if it's over a list, I would definitely write
for (index in list.indices) {
(unless
for ((index, elem) in list.withIndex()) {
works better in context, of course)
m

Mark

04/12/2023, 5:10 AM
Ok, but in this case there is no direct access to the list
j

Jan

04/12/2023, 7:24 PM
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

Jan

04/12/2023, 8:36 PM
Exactly
m

Marcin Wisniowski

04/17/2023, 10:06 AM
Also if you need to use
continue
in your loop body, you can't use
repeat
.