For循环范围必须具有"iterator()"方法 [英] For-loop range must have an 'iterator()' method

查看:46
本文介绍了For循环范围必须具有"iterator()"方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我那里有这个奇怪的错误

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

推荐答案

如果使用:

for(item in items)

items 需要一个 iterator 方法;您正在遍历对象本身.

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

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

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]
}

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

这两个方法均创建一个 IntRange ,该扩展了 IntProgression ,该实现实现了 Iterable .如果您使用其他数据类型(即float,long,double),则相同.

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){}

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

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

这篇关于For循环范围必须具有"iterator()"方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆