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

petrrr33
  • 583
  • 9
  • 24

2 Answers2

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
}
Cililing
  • 4,303
  • 1
  • 17
  • 35
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] }
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • `it` is the value inside the array, not the index. The answer i received below worked for me – petrrr33 Apr 02 '19 at 12:08
  • 1
    No, `it` is the default name for the lambda's parameter (see https://kotlinlang.org/docs/reference/lambdas.html#it-implicit-name-of-a-single-parameter). In `map` it will be the value inside the array; in `IntArray`'s constructor it will be the index. – Alexey Romanov Apr 02 '19 at 12:17