Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can you not specify var/val loops in Kotlin? [closed]

Tags:

kotlin

Why can't you specify a val or var type in for loop's in Kotlin. For example, I would like to be able to do

    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
    }

But instead I have to do this

    var i = 0
    while (i < data.size) {
        for (j in 0..bytes.size - 1) {
            bytes[j] = data[i++]
        }
        //do stuff
    }
like image 431
Jonathan Beaudoin Avatar asked Mar 13 '23 16:03

Jonathan Beaudoin


1 Answers

Your example is slightly different from Java's typical for(int i=0;i<data.size;i++) example. In the Kotlin version 'i' is actually an element of the range in which case i++ doesn't make sense. It just so happens that the range you have is a list of indexes.

The way you are using the Kotlin for loop is much closer to Java's foreach loop for(i : indexes).

like image 167
Frod Mann Avatar answered Mar 15 '23 22:03

Frod Mann