jmarkstar
jmarkstar

Reputation: 1335

How Can I do a for with many variables

I'd like to know how I can do this for in Kotlin:

for(int i=arr.length-1, j=0; i>=0 && j<reverse.length; i--, j++){
    reverse[j] = arr[i];
}

Thanks

Upvotes: 2

Views: 112

Answers (2)

Januson
Januson

Reputation: 4841

If you are Using IntelliJ Idea, you can use Java to Kotlin code conversion. Result for your code is:

var i = arr.length - 1
var j = 0
while (i >= 0 && j < reverse.length) {
    reverse[j] = arr[i]
    i--
    j++
}

But if all you need is reverse of your array, then you can just call Array's method reversedArray.

val arr = arrayOf("a", "b", "c")
val reversed = arr.reversedArray()

Upvotes: 3

As far as i know u can't have multiple indexes in for loop

As a solution u can use Array.reverse() function or just calculate the second index:

    val array = arrayOf(1, 2, 3)

    val lastIndex = array.size - 1
    for (i in 0..lastIndex)
        array[lastIndex - i] = array[i]

for syntaxis

Upvotes: 1

Related Questions