Add another Array to this Array in Kotlin
To add another Array to this Array in Kotlin, you can use Addition Assignment operator. Use the operator and pass the Array as left operand, and the other Array as right operand.
The syntax to add another Array anotherArray
to this Array arr
is
arr += anotherArray
Elements of the second Array are appended to the first Array.
Examples
Add otherFruits Array to the fruitNames Array
In the following program, we take two Arrays of strings: fruitNames
and otherFruits
. We use Addition Assignment operator to add the elements of the otherFruits
Array to the fruitNames
Array.
Kotlin Program
fun main(args: Array<String>) {
var fruitNames = arrayOf("apple", "banana", "cherry")
var otherFruits = arrayOf("mango", "fig")
fruitNames += otherFruits
println(fruitNames.contentToString())
}
Output
[apple, banana, cherry, mango, fig]