This article explores different ways to join two arrays in Kotlin.

The solution should generate a new array containing all elements of the first array, followed by all the second array elements while preserving the original order of elements in both arrays.

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:

Download Code

 
An equivalent way is to use the plus() function.

Download Code

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.

Download Code

3. Using MutableList

You can also create a MutableList object and add all elements of the first array, followed by all elements of the second array. Finally, return the list as an array.

Download Code

 
This can be shortened to:

4. Using System.arraycopy() function

The idea is to allocate memory to the new array to accommodate all the elements present in both arrays and use System.arraycopy() to copy given arrays into the new array, as shown below:

Download Code

 
You can replace the first System.arraycopy() call to the copyOf() function:

5. Using Java 8 Stream

We can use Stream in Kotlin to merge two arrays. This can be easily done using the Stream.concat() function:

Download Code

That’s all about joining two arrays in Kotlin.