In Java:
for(int j = 0; j < 6 && j < ((int)abc[j] & 0xff); j++) {
// ...
}
How we can make this loop in Kotlin?
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`
}
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 {
// ...
}
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++
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With