I recently started learning Kotlin and the one thing I noticed is the for-loop syntax of Kotlin is different from traditional for-loop syntax and for me it is a bit confusing...I tried to search it on google but didn't get my answer.
How would I duplicate the following Java for loop?
for (int i = 0; i <= 100; i++) {
System.out.println(i);
}
Here is a Java for loop to iterate 100 times:
for (int i = 0; i <= 100; i++) {
System.out.println(i);
}
Here is the Kotlin equivalent:
for (i in 0..100) {
println(i)
}
Here is a Java for loop that will iterate through a list:
for (int i = 0; i < list.size(); i++) {
Object item = list.get(i);
// Do something with item
}
Kotlin equivalent:
for (i in list.indices) {
val item = list[i]
// Do something with item
}
Here is another Kotlin equivalent for iterating a list:
for (i in 0 until list.size) {
val item = list[i]
// Do something with item
}
Java for-each loop:
for (Object item : list) {
// Do something with item
}
Kotlin for-each loop:
for (item in list) {
// Do something with item
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With