For循环范围必须具有'iterator()'方法

Fil*_*ppo 1 android kotlin

我在那里遇到了这个奇怪的错误

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

}
Run Code Online (Sandbox Code Playgroud)

我找到了关于这个错误的类似答案,但没有人为我工作

Zoe*_*Zoe 9

如果您使用:

for(item in items)
Run Code Online (Sandbox Code Playgroud)

items需要一种iterator方法; 你在迭代对象本身.

如果要迭代范围中的int,则有两个选项:

for(i in 0..limit) {
    // x..y is the range [x, y]
}
Run Code Online (Sandbox Code Playgroud)

要么

for(i in 0 until limit) {
    // x until y is the range [x, y>
}
Run Code Online (Sandbox Code Playgroud)

这两个都创建了一个IntRange扩展的IntProgression实现Iterable.如果使用其他数据类型(即float,long,double),则它们是相同的.


作为参考,这是完全有效的代码:

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

因为List是一个Iterable.Int不是,这就是你的代码不起作用的原因.

  • 只需添加第三个选项:```for(i in 10 downto 0) { }``` (3认同)
  • 它并不完全有效,因为它需要是 `List&lt;Something&gt;`,而不仅仅是 `List` :) (2认同)