Skip to main content

How to concatenate two arrays in Kotlin

How to concatenate two arrays in Kotlin.

Here's a detailed step-by-step tutorial on how to concatenate two arrays in Kotlin:

Step 1: Create the arrays

First, let's create two arrays that we want to concatenate. You can create arrays using the arrayOf() function or with the array constructor.

val array1 = arrayOf(1, 2, 3)
val array2 = arrayOf(4, 5, 6)

Step 2: Use the plus() function

In Kotlin, you can concatenate two arrays using the plus() function. This function takes another array as a parameter and returns a new array that contains the elements of both arrays.

val concatenatedArray = array1.plus(array2)

Step 3: Print the concatenated array

To verify the result, let's print the concatenated array using a loop or the joinToString() function.

Using a loop:

for (element in concatenatedArray) {
println(element)
}

Using the joinToString() function:

println(concatenatedArray.joinToString(", "))

Step 4: Alternative method using the spread operator

In addition to using the plus() function, Kotlin also provides an alternative method to concatenate arrays using the spread operator (*). This operator allows you to expand the elements of an array and use them as individual arguments.

val concatenatedArray = (*array1, *array2)

Step 5: Print the concatenated array (alternative method)

You can print the concatenated array using the same methods as in Step 3.

Using a loop:

for (element in concatenatedArray) {
println(element)
}

Using the joinToString() function:

println(concatenatedArray.joinToString(", "))

That's it! You've successfully concatenated two arrays in Kotlin. Remember to choose the method that best suits your needs – using the plus() function or the spread operator.