Home > Software design >  How do I step through a fixed range in a loop in Kotlin where the step value changes on every iterat
How do I step through a fixed range in a loop in Kotlin where the step value changes on every iterat

Time:11-30

It seems Kotlin has taken away the ability to do common, basic loops or I haven't found the right documentation.

Given the following Java loop, I can roughly convert it to the kotlin below it (included so you can maybe understand where my current mistake has originated. This method was not easy to discover, so it may not be the correct approach at all)

for (int i=start; i < end; i  )   // base java
for (i in start until end)        // equivalent kotlin 

But what about when I need to support stepping instead of incrementing one at a time? Given this Java loop:

for (int offset = 0; offset < length; ) {
    int count = 1
    //stuff that assigns count
    offset  = count;
}

This Kotlin "equivalent" code gives an assignment error because i is in fact a val not a var (and I may not declare it as a var):

for (i in offset until length) {
    var count = 1
    //stuff that assigns count
    offset  = count;
}

How do I step through a fixed range, where the step value changes on every iteration?

CodePudding user response:

This syntax in Java

for (int i = 0; i < length; i  ) {

}

is shorthand for

int i = 0;
while (i < length) {

    i  ;
}

for which the equivalent Kotlin code would be

var i = 0
while (i < length) {

    i  
}

Likewise, your example code

for (int offset = 0; offset < length; ) {
    int count = 1;
    //stuff that assigns count
    offset  = count;
}

is shorthand for

int offset = 0;
while (offset < length) {
    int count = 1;
    //stuff that assigns count
    offset  = count;
}

for which the equivalent Kotlin code is:

var offset = 0
while (offset < length) {
    var count = 1
    //stuff that assigns count
    offset  = count
}

CodePudding user response:

As requested, a proper example:

var i = 0

while (i < end) {
    val count = 1

    i  = count
}
  • Related