2

I can initialize an array in Kotlin like this:

val mArr = Array<Int>(5) {0}

and I'll have the following array [0,0,0,0,0]

The thing is, I need to initialise an array and put the values of another array into it. i.e:

initialArray = [1, 4, 5 ,-2, 7] val offset = 5

And should get mArr = [6, 9, 10, 3, 12]

Is there a way to set the value of each mArr[i] based on each initialArray[i]?

Something like

val mArr = Array<Int>(initialArray.size) { offset + initialArray[index]}

Without wrapping it in a for loop

2 Answers 2

4

There is map function for array.

So:

val initialArray = arrayOf(1, 4, 5 ,-2, 7)
val offset = 5
val newArray = initialArray.map { it + offset }.toTypedArray()

But this way you create new array without modifying the old one. If you want modify old array you can use forEachIndexed extension method:

initialArray.forEachIndexed { index, value ->
    initialArray[index] = initialArray[index] + offset

    // or:
    initialArray[index] = value + offset
}
Sign up to request clarification or add additional context in comments.

Comments

0
val mArr = Array<Int>(initialArray.size) { offset + initialArray[index] }

already nearly works. It's just that index isn't defined here. You want it to be the function's parameter, so { index -> offset + initialArray[index] } or shorter { offset + initialArray[it] }. Also, for this you probably want IntArray instead of Array<Int> (and for initialArray as well). Combining these changes:

val mArr = IntArray(initialArray.size) { offset + initialArray[it] }

2 Comments

it is the value inside the array, not the index. The answer i received below worked for me
No, it is the default name for the lambda's parameter (see kotlinlang.org/docs/reference/…). In map it will be the value inside the array; in IntArray's constructor it will be the index.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.