What is the equivalent code of this version of for loop in Kotlin?
for(int i = 0; i < 5 ; i++) {
//Body
}
What is the equivalent code of this version of for loop in Kotlin?
for(int i = 0; i < 5 ; i++) {
//Body
}
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.
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
}