Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make multiconditional for loop in kotlin

Tags:

kotlin

In Java:

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

How we can make this loop in Kotlin?

like image 905
nehal jajoo Avatar asked Jul 21 '17 06:07

nehal jajoo


4 Answers

I'd suggest to use a more functional approach like

(0..5).takeWhile {
    it < (abc[it].toInt() and 0xff) // or `as Int` if array is not numeric
}.forEach {
    // do something with `it`
}
like image 186
guenhter Avatar answered Nov 14 '22 13:11

guenhter


If you don't mind creating a new ArrayList instance, it can be done like this:

(0..5).takeWhile { it < (abc[it] as Int and 0xff) }
        .forEach {
            // ...
        }
like image 38
BakaWaii Avatar answered Nov 14 '22 13:11

BakaWaii


Note: the .takeWhile { ... }.forEach { ... } approach suggested in some answers is not equivalent to the Java for loop. The range is first processed with .takeWhile { ... } and only then the prefix it returned is iterated over. The problem is that the execution of the .forEach { ... } body won't affect the condition of .takeWhile { ... }, which has already finished execution by the time the body gets called on the first item.

(see this runnable demo that shows how the behavior is different)

To fix this, you can use Sequence<T>. In constrast with eager evaluation over Iterable<T>, it won't process the whole set of items with .takeWhile { ... } and will only check them one by one when .forEach { ... } is up to process a next item. See: the difference between Iterable<T> and Sequence<T>.

To use the Sequence<T> and achieve the behavior that is equivalent to the Java loop, convert the range .toSequence():

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

Alternatively, just use the while loop:

var j = 0
while (j < 6 && j < (abc[j] as Int and 0xff)) {
    // do something
    j++
}
like image 30
hotkey Avatar answered Nov 14 '22 13:11

hotkey


This is how the kotlin version will look like.

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 are using IntelliJ, here is a link to help you convert from Java to Kotlin. IntelliJ Java to Kotlin.

like image 40
Alf Moh Avatar answered Nov 14 '22 13:11

Alf Moh