Kotlin – Add element to Array

Add an element to Array in Kotlin

To add an element to given Array in Kotlin, you can use Addition Assignment operator. Use the operator and pass the Array as left operand, and element as right operand.

The syntax to add an element e to the Array arr is

arr += e

Examples

Add an element to Array of Strings

In the following program, we take an Array of strings fruitNames with three initial elements in the Array, and add a new element "mango" to the Array.

Kotlin Program

fun main(args: Array<String>) {
    var fruitNames = arrayOf("apple", "banana", "cherry")
    fruitNames += "mango"
    println(fruitNames.contentToString())
}

Output

[apple, banana, cherry, mango]