Skip to content
Advertisement

Convert Java loop to Kotlin [closed]

I’m studying implementation with Kotlin. When I implement Kotlin version by below situation, I can’t imagine cool way.

for(i = 0 ; i + 8 <= table.size; i++){
 for(j = 0 ; j + 8 <= table[0].size; j++{
  whatever
 }
}

Above code is Java version

for(i in 0 until table.size){
 if(i+8 > table.size)break
  for(j in until table[0].size){
    if(j+8 > table[0].size)break
      whatever
   }
}

Above is Kotlin version which I think.

Is this fine way?

Advertisement

Answer

You can just move the -8 into the upper limit, and since you include (<=) the upper limit you shouldn’t be using until, but the regular range expansion with two dots.

So it becomes:

for (i in 0..table.size-8){
    for (j in 0..table[i].size-8){}
}

(I imagine you would also want to replace the magical number eight with a variable with a meaningful name)

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement