Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Java and Kotlin for-loop syntax?

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);
}
like image 410
Hammad Hassan Avatar asked Apr 25 '26 04:04

Hammad Hassan


1 Answers

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
}
like image 149
spierce7 Avatar answered Apr 28 '26 01:04

spierce7



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!