How to make multiconditional for a loop in kotlin

In Java:

for(int j = 0; j < 6 && j < ((int)abc[j] & 0xff); j++) { 
  // ...
}

How can we do this loop in Kotlin?

+4
source share
6 answers

I would suggest using a more functional approach, for example

(0..5).takeWhile {
    it < (abc[it].toInt() and 0xff) // or `as Int` if array is not numeric
}.forEach {
    // do something with `it`
}
+8
source

If you don't mind creating a new instance of ArrayList, you can do this as follows:

(0..5).takeWhile { it < (abc[it] as Int and 0xff) }
        .forEach {
            // ...
        }
+4
source

. .takeWhile { ... }.forEach { ... }, , Java for. .takeWhile { ... }, , , . , .forEach { ... } .takeWhile { ... }, , .

(. , , )

, Sequence<T>. Iterable<T>, .takeWhile { ... } , .forEach { ... } . . Iterable<T> Sequence<T>.

Sequence<T> , Java, .toSequence():

(0..5).asSequence()
    .takeWhile { it < (abc[it].toInt() and 0xff) }
    .forEach {
        // Use `it` instead of `j`
    }

while:

var j = 0
while (j < 6 && j < (abc[j] as Int and 0xff)) {
    // do something
    j++
}
+3

kotlin.

var j = 0
while (j < 6 && j < (abc[j] as Int and 0xff)) {
    // do something
    j++
}

You can convert Java to Kotlin online here. Try Kotlin . Also, if you use IntelliJ, here is a link that will help you convert from Java to Kotlin. IntelliJ Java for Kotlin.

+2
source

I would move the part j < ((int)abc[j] & 0xff)to an if-test inside the loop. Then you can do this:

for (j in 0..5) {
    if (j < (abc[j].toInt() and 0xff)) {
      // Do stuff here
    } else break
}
-1
source

This is the output of the intellij plugin for conversion:

 var j = 0
 while (j < 6 && j < abc[j] as Int and 0xff) {
      j++
      // ...
 }
-1
source

Source: https://habr.com/ru/post/1681936/


All Articles