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

Viewed 12252

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

1 Answers

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.

Related