Issue
How to add a value to each integer value to array/list. I searched but didn't find any solution in kotlin.
I tried in this way but it is showing error..
fun main() {
val arrayNum = arrayOf(2,3,9)
val newArrayNum = arrayNum.foreach { it ->
it += 2
}
}
Solution
You can just use map
to create a new list with your new elements and then transform it back to an array:
val newArrayNum = arrayNum.map { it + 2 }.toTypedArray()
This is the less performant solution since it will create a new ArrayList
under the hood and a new array.
To avoid the creation of the ArrayList
you can do:
val newArrayNum = IntArray(arrayNum.size) { index ->
arrayNum[index] + 2
}
To modify the content of the original array (without creating new arrays or ArrayList
) you can do:
arrayNum.forEachIndexed { index, value ->
arrayNum[index] = value + 2
}
Answered By - Giorgio Antonioli
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.