2

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?

3
  • 4
    In Kotlin, for iterates over only iterators. So unless you can abstract away the stepping in an iterator, you'll have to use a while loop Commented Nov 29, 2021 at 14:47
  • 1
    thanks @Peter, that might be why I could't find what I was looking for then since I've been googling for-loops specifically. An answer with the actual syntax would be useful to close this question. It seem like while still requires me to make a var outside of the loop Commented Nov 29, 2021 at 14:51
  • It does require declaration outside the loop statement - it would be the same as in Java. Commented Nov 29, 2021 at 15:00

2 Answers 2

2

As requested, a proper example:

var i = 0

while (i < end) {
    val count = 1

    i += count
}
Sign up to request clarification or add additional context in comments.

Comments

2

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.