0
0
KotlinHow-ToBeginner · 3 min read

How to Merge Two Lists in Kotlin: Simple Guide

In Kotlin, you can merge two lists using the + operator or the plus() function. Both create a new list containing elements from both lists without changing the originals.
📐

Syntax

To merge two lists in Kotlin, use either the + operator or the plus() function.

  • list1 + list2: Combines list1 and list2 into a new list.
  • list1.plus(list2): Does the same as the + operator.

Both ways return a new list and do not modify the original lists.

kotlin
val list1 = listOf(1, 2, 3)
val list2 = listOf(4, 5, 6)

val merged1 = list1 + list2
val merged2 = list1.plus(list2)
💻

Example

This example shows how to merge two lists of numbers using both the + operator and the plus() function. It prints the merged lists to demonstrate the result.

kotlin
fun main() {
    val list1 = listOf(10, 20, 30)
    val list2 = listOf(40, 50, 60)

    val mergedWithPlus = list1 + list2
    val mergedWithFunction = list1.plus(list2)

    println("Merged with + operator: $mergedWithPlus")
    println("Merged with plus() function: $mergedWithFunction")
}
Output
Merged with + operator: [10, 20, 30, 40, 50, 60] Merged with plus() function: [10, 20, 30, 40, 50, 60]
⚠️

Common Pitfalls

One common mistake is trying to merge lists using add() on immutable lists, which causes errors because listOf() creates read-only lists.

Also, remember that + and plus() do not change the original lists but return a new merged list.

kotlin
fun main() {
    val list1 = listOf(1, 2, 3)
    val list2 = listOf(4, 5, 6)

    // Wrong: Trying to add to immutable list
    // list1.addAll(list2) // This will cause a compile error

    // Right: Use + operator or plus() function
    val merged = list1 + list2
    println(merged)
}
Output
[1, 2, 3, 4, 5, 6]
📊

Quick Reference

Summary of ways to merge lists in Kotlin:

MethodDescriptionModifies Original List?
list1 + list2Returns a new list combining both listsNo
list1.plus(list2)Same as + operator, returns new listNo
mutableList1.addAll(list2)Adds all elements of list2 to mutableList1Yes (only for mutable lists)

Key Takeaways

Use the + operator or plus() function to merge two lists in Kotlin.
Both methods return a new list and do not change the original lists.
Immutable lists cannot be changed with add or addAll methods.
For mutable lists, addAll() can merge by modifying the original list.
Merging lists is simple and safe with Kotlin's built-in operators.