为什么不能在Kotlin中指定var / val循环?

时间:2016-04-05 20:43:53

标签: kotlin

为什么不能在Kotlin中为for循环指定val或var类型。例如,我希望能够做到

    for (var i in 0...data.size - 1) {
        for (j in 0..bytes.size - 1) {
            bytes[j] = data[i++]//cant do i++ in current kotlin because "i" is val
        }
        //do stuff
    }

但我必须这样做

    var i = 0
    while (i < data.size) {
        for (j in 0..bytes.size - 1) {
            bytes[j] = data[i++]
        }
        //do stuff
    }

2 个答案:

答案 0 :(得分:4)

您的示例与Java的典型for(i : indexes)示例略有不同。 在Kotlin版本&#39; i&#39;实际上是i ++没有意义的范围的一个元素。碰巧你所拥有的范围是一系列索引。

使用Kotlin for循环的方式更接近Java的foreach循环 // These will be zero if the dygraph's div is hidden. In that case, // use the user-specified attributes if present. If not, use zero // and assume the user will call resize to fix things later. this.width_ = div.clientWidth || attrs.width || 440; this.height_ = div.clientHeight || attrs.height ||320;

答案 1 :(得分:3)

我认为,因为Kotlin是一种试图轻松尊重大多数函数式编程概念的语言,所以它更喜欢禁止这种行为。此外,在bytes数组包含的元素多于数据数组的情况下,初始代码可能存在的一个可能的问题是OutOfBoundException。

相关问题