For-loop range must have an 'iterator()' method

10,567

If you use:

for(item in items)

items needs an iterator method; you're iterating over the object itself.

If you want to iterate an int in a range, you have two options:

for(i in 0..limit) {
    // x..y is the range [x, y]
}

Or

for(i in 0 until limit) {
    // x until y is the range [x, y>
}

Both of these creates an IntRange, which extends IntProgression, which implements Iterable. If you use other data types (i.e. float, long, double), it's the same.


For reference, this is perfectly valid code:

val x: List<Any> = TODO("Get a list here")
for(item in x){}

because List is an Iterable. Int is not, which is why your code doesn't work.

Share:
10,567

Related videos on Youtube

Filippo
Author by

Filippo

Updated on June 04, 2022

Comments

  • Filippo
    Filippo almost 2 years

    I'm having this weird error right there

    val limit: Int = applicationContext.resources.getInteger(R.integer.popupPlayerAnimationTime)
    for(i in limit) {
    
    }
    

    I've found similar answer about that error but no one worked for me

  • Alexey Romanov
    Alexey Romanov over 5 years
    It isn't quite perfectly valid because it needs to be List<Something>, not just List :)
  • Zoe stands with Ukraine
    Zoe stands with Ukraine over 5 years
    Nice catch, I fixed it. Thanks ^^
  • OroshiX
    OroshiX over 4 years
    Just to add a 3rd option: for(i in 10 downto 0) { }