14

Is it possible to continue n times in a kotlin loop?

for(i in 0..n){
    doSomething()
    if(condition){
       //manipulate n
    }
}

Since i for some reason is a val I cannot seem to reinitialize it in the loop.

Jonas Grønbek
  • 1,709
  • 2
  • 22
  • 49
  • 2
    I think you'd be better off with a while loop. But depends on what you're actually doing – Tim Feb 12 '19 at 14:21
  • You very rarely have to use a standard `for` or `while` loop in Kotlin. Kotlin has many advanced tools to solve most common problems. What exactly are you trying to acheive with that loop? – m0skit0 Feb 12 '19 at 14:24
  • *This is the function giving me trouble* - be clear. What are you trying to do and what issue do you have – Tim Feb 12 '19 at 15:05
  • I understand you want to substract two strings and return an array of ints. That makes no sense to me, can you please explain what are the parameters and the return value? – m0skit0 Feb 12 '19 at 15:07
  • Isn't it easier to convert the strings to Int/Long and then operate? As simple as `String#toInt()` – m0skit0 Feb 12 '19 at 15:23
  • @m0skit0 it would be harder to do pure binary calculations in base10. The goal of the application is for me to learn to calculate in binary, therefore i treat it like a real binary calculation – Jonas Grønbek Feb 12 '19 at 15:27
  • Ok then. You should use a `while` if you want to modify the value of the counter inside the loop. Note that this is considered bad practice, maybe you want to consider another algorithm (also note that substraction in computers is actually implemented as an addition with two's complement). – m0skit0 Feb 12 '19 at 15:31

1 Answers1

34
repeat(n){
    blah()
}

Will execute blah() n times.

John Doe
  • 1,003
  • 12
  • 14
  • why this didn't get suggested immediately baffles me. Considering this question has 600 views, I thank you for your answer even though I am not working with kotlin anymore – Jonas Grønbek Oct 23 '20 at 18:12
  • 2
    No problem :) Hopefully it will be helpful for somebody else. – John Doe Oct 23 '20 at 19:48
  • And if you want to have a running count, what do you do? For your example, what if the function had a parameter, such as `blah(count)`? – SMBiggs Jun 03 '21 at 03:37
  • 1
    repeat(3) { index -> blah(index) } https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/repeat.html – John Doe Jun 04 '21 at 04:38
  • The issue with repeat is, that it's not straightforward to finish execution earlier, by using `break`, like it is possible for instance for `for` loop – Tom Raganowicz Jun 30 '22 at 07:54