This article explores different ways to concatenate byte arrays in Kotlin.

1. Using + operator

The standard solution to concatenate byte arrays in Kotlin is using the + operator. It returns an array containing all elements of the two arrays. For example,

Download Code

 
We can also use the plus() function, which returns an array containing all elements of the original array and followed by all elements of the specified array. This is effectively the same as using the + operator.

Download Code

2. Using ByteArrayOutputStream

The idea here is to write bytes from each of the byte arrays to the output stream and call the toByteArray() function to get the output stream’s contents as a byte array. This can be implemented as follows in Kotlin using vararg.

Download Code

Output:

Apple, Google

3. Using ByteBuffer

Another solution is to use the ByteBuffer#put() function to transfer bytes from each of the byte arrays into a buffer and call the array() function to get the byte array from the buffer.

Download Code

Output:

AppleGoogle

 
To concatenate the arbitrary number of byte arrays, create a utility function that takes varargs.

Download Code

Output:

Apple, Google

4. Using System.arraycopy() function

Another elegant solution is to make two calls to System.arraycopy(), which can efficiently copy contents of an array to the destination array. Here’s the complete code:

Download Code

Output:

Apple, Google

That’s all about concatenating byte arrays in Kotlin.