Concatenate two arrays in Kotlin
This article explores different ways to concatenate two arrays in Kotlin. The requirement is to generate a new array that contains all elements of the first array, followed by all elements of the second array.
1. Using Plus Operator
A simple and fairly efficient solution to combine two arrays in Kotlin is with the plus operator. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun concatenate(a: IntArray, b: IntArray): IntArray { return a + b } fun main() { val A = intArrayOf(1, 2, 3) val B = intArrayOf(4, 5) val concat = concatenate(A, B) println(concat.contentToString()) // [1, 2, 3, 4, 5] } |
An equivalent way is to use the plus() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun concatenate(a: IntArray, b: IntArray): IntArray { return a.plus(b) } fun main() { val A = intArrayOf(1, 2, 3) val B = intArrayOf(4, 5) val concat = concatenate(A, B) println(concat.contentToString()) // [1, 2, 3, 4, 5] } |
2. Using Spread Operator
This can also be done using the Spread operator (prefix the array with *). You can pass the contents of both arrays to the Array constructor using the Spread operator.
|
1 2 3 4 5 6 7 8 |
fun main() { val A = intArrayOf(1, 2, 3) val B = intArrayOf(4, 5) val concat = intArrayOf(*A, *B) println(concat.contentToString()) // [1, 2, 3, 4, 5] } |
3. Using System.arraycopy() function
The System class’s arraycopy() function provides a convenient and efficient way to copy elements of an array into another array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
fun concatenate(a: IntArray, b: IntArray): IntArray { val c = IntArray(a.size + b.size) System.arraycopy(a, 0, c, 0, a.size) System.arraycopy(b, 0, c, a.size, b.size) return c } fun main() { val A = intArrayOf(1, 2, 3) val B = intArrayOf(4, 5) val concat = concatenate(A, B) println(concat.contentToString()) // [1, 2, 3, 4, 5] } |
4. Using copyOf() function
You can also use the copyOf() function to copy elements of the first array, followed by the System.arraycopy() function to copy elements of the second array, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun concatenate(a: IntArray, b: IntArray): IntArray { val result = a.copyOf(a.size + b.size) System.arraycopy(b, 0, result, a.size, b.size) return result } fun main() { val A = intArrayOf(1, 2, 3) val B = intArrayOf(4, 5) val concat = concatenate(A, B) println(concat.contentToString()) // [1, 2, 3, 4, 5] } |
That’s all about concatenating two arrays in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)