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.
Related videos on Youtube
Author by
Filippo
Updated on June 04, 2022Comments
-
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 over 5 yearsIt isn't quite perfectly valid because it needs to be
List<Something>
, not justList
:) -
Zoe stands with Ukraine over 5 yearsNice catch, I fixed it. Thanks ^^
-
OroshiX over 4 yearsJust to add a 3rd option:
for(i in 10 downto 0) { }