Kotlin plus()

Kotlin plus()

In Kotlin, the plus() function is used to concatenate two collections or add elements to a collection. It is commonly used with lists, sets, and other collection types.

This function provides a convenient way to combine multiple collections into a new one or add elements to an existing collection without modifying the original collections.

In this tutorial, we’ll explore the syntax of the plus() function and provide examples of its usage in Kotlin.

Syntax

The syntax of the plus() function depends on the type of collections involved:

operator fun <T> Collection<T>.plus(elements: Iterable<T>): List<T>

The plus() function is an extension function for collections, and it returns a new list containing the elements of the original collection followed by the elements of the specified iterable.

Examples for plus() function

1. Using plus() to Concatenate Integer Arrays

In this example, we’ll use plus() to concatenate two lists of integers.

Kotlin Program

fun main() {
    val array1 = intArrayOf(100, 200, 300)
    val array2 = intArrayOf(400, 500, 600)

    // Using plus to concatenate arrays
    val concatenatedArray = array1.plus(array2)

    // Printing the original and concatenated arrays
    println("Array 1: ${array1.joinToString(", ")}")
    println("Array 2: ${array2.joinToString(", ")}")
    println("Concatenated Array: ${concatenatedArray.joinToString(", ")}")
}

Output

Array 1: 100, 200, 300
Array 2: 400, 500, 600
Concatenated Array: 100, 200, 300, 400, 500, 600

In this example, the plus() function is used to concatenate two arrays of integers. The original and concatenated arrays are then printed to the console.

2. Using plus() to Concatenate Lists

In this example, we’ll use plus() to concatenate two lists of integers.

Kotlin Program

fun main() {
    val list1 = listOf("apple", "banana")
    val list2 = listOf("cherry", "fig", "mango")

    // Using plus to concatenate lists
    val concatenatedList = list1.plus(list2)

    // Printing the original and concatenated lists
    println("List 1: ${list1.joinToString(", ")}")
    println("List 2: ${list2.joinToString(", ")}")
    println("Concatenated List: ${concatenatedList.joinToString(", ")}")
}

Output

List 1: apple, banana
List 2: cherry, fig, mango
Concatenated List: apple, banana, cherry, fig, mango

In this example, the plus() function is used to concatenate two lists of strings. The original and concatenated lists are then printed to the console.

Summary

In this tutorial, we’ve covered the plus() function in Kotlin, its syntax, and how to use it for concatenating two collections or adding elements to a collection.