0

What is the equivalent code of this version of for loop in Kotlin?

for(int i = 0; i < 5 ; i++) {
    //Body            
}
takendarkk
  • 3,347
  • 8
  • 25
  • 37
Devrath
  • 42,072
  • 54
  • 195
  • 297

3 Answers3

0

Just

for(i in 0 until 5){
    //body
}
Andrei Tanana
  • 7,932
  • 1
  • 27
  • 36
0
for(i in 0 until 5) {
    // body
}

Where until is an IntRange from 0 to n-1, aka 0..n-1.


Technically if you don't want to use an IntRange, then it's

var i = 0
while(i < 5) {
    // Body
    i++
}

Though I haven't seen that used particularly often.

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
  • 1
    There's also standard function [`repeat`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/repeat.html) which can be used instead if starting index is 0. – Pawel Feb 09 '19 at 19:22
  • Ah yes sorry I forgot even though I've used it before – EpicPandaForce Feb 09 '19 at 19:54
-1

In this simple case the shortest way would be to use repeat:

repeat(5) {
    println(it) // 0, 1, 2, 3, 4
}

If you need to specify the start, an IntRange with forEach would be a good idea:

(0 until 5).forEach {
    println(it) // 0, 1, 2, 3, 4
}

If you want to include the end you would create a usual IntRange.

(0..5).forEach {
    println(it) // 0, 1, 2, 3, 4, 5
}
Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121