Skip to content Skip to sidebar Skip to footer

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 t

Solution 1:

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) {
  valitem= list[i]

  // Do something with item
}

Here is another Kotlin equivalent for iterating a list:

for (i in 0 until list.size) {
  valitem= 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
}

Solution 2:

val scanner = Scanner(System.`in`)

var nos = Array<Int>(5) { 0 }

for (i in1..3) {
    nos[i] = scanner.nextInt()
}

println("Given values $nos")

Here, you can see i in 1..3 and you do not need to declare var i : Int = 1 as it'll be declared for you in the loop. Nor do you need the i = i+1 inside the loop for that matter.

Post a Comment for "Difference Between Java And Kotlin For-loop Syntax?"