I want to make one array from two arrays.
I tried to do use +:
var array1 = intArrayOf(1,2,3)
var array2 = intArrayOf(4,5,6)
var array3 = array1 + array2
But it is not working unfortunately... How can I combine them?
I want to make one array from two arrays.
I tried to do use +:
var array1 = intArrayOf(1,2,3)
var array2 = intArrayOf(4,5,6)
var array3 = array1 + array2
But it is not working unfortunately... How can I combine them?
Actually, your exact code works for me. Tried it on multiple Kotlin versions. You can find the operator fun IntArray.plus(elements: IntArray): IntArray
function that's being used for this in the docs here, and its source here.
var array1 = intArrayOf(1, 2, 3) // 1, 2, 3
var array2 = intArrayOf(4, 5, 6) // 4, 5 ,6
var array3 = array1 + array2 // 1, 2, 3, 4, 5, 6
Are you perhaps looking to do something different, like add the elements one by one and create a new array of length 3? You can do that like this:
val array4 = array1.zip(array2, Int::plus).toTypedArray() // 5, 7, 9
The extra toTypedArray
call is necessary only if you actually need an array, otherwise you can use the List<Int>
that the zip
function returns.
Using the spread operator:
var array3 = intArrayOf(*array1, *array2)
This could be especially useful when you need to add some custom elements between the arrays, like intArrayOf(7, *array1, 8, 9, *array2, 10, 11)
.
Note spreading is much more efficient than plus
-ing, because it creates only one resulting array. Using an equivalent plus version of the above spread example may use 5x more space and take 5x more time.
I am adding some other ways to merge two arrays.
var array1 = intArrayOf(1, 2, 3)
var array2 = intArrayOf(4, 5, 6)
Way 1:
var array3 = array1 + array2
print(array3.asList())
It will print [1, 2, 3, 4, 5, 6]
. This one is given above.
You can replace the +
by plus()
method.
var array3 = array1.plus(array2)
print(array3.asList())
It will also work the same. When you are using +
, at that time it actually calls the plus()
method.
Way 2:
var array3 = array1.union(array2.asList())
print(array3)
It will print [1, 2, 3, 4, 5, 6]
.
union()
method can take a collection as parameters. It can merge two arrays but it returns a Set. So, we will have unique data but it will merge two arrays.
Way 3:
var mergedArraySize = array1.size + array2.size
var mergedArray = IntArray(mergedArraySize)
var pos = 0;
for (value in array1) {
mergedArray[pos] = value
pos++
}
for (value in array2) {
mergedArray[pos] = value
pos++
}
print(mergedArray.asList())
It will also print [1, 2, 3, 4, 5, 6]
.