Filippo
Filippo

Reputation: 294

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

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

Upvotes: 5

Views: 19712

Answers (1)

Zoe - Save the data dump
Zoe - Save the data dump

Reputation: 28238

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.

Upvotes: 18

Related Questions