Let us say, we have a List that contains three names, 'Mohan', 'Kriti' and 'Salim'. And we want to insert a new List with two names 'Sia' and 'Andrew' at the end of the List.
There are two ways by which we can join or extend List.
At first let us see the Joining of two Lists using '+' operator.
fun main() { var x = mutableListOf("Mohan", "Kriti", "Salim") var y = mutableListOf("Sia", "Andrew") var z = x + y println(z) }
So, in the above code we have created a 'List' and initialised to the variable 'x'.
Below is how the values are positioned in the List,
Also we have another List that contains, 'Sia' and 'Andrew'.
Next, we have used the '+' operator to add the the Lists 'x' and 'y'.
And the Lists 'x' and 'y'is joined and initialised to a new List 'z'.
And we get the below output,
Let us rewrite the same example using the 'addAll()' Function.
fun main() { var x = mutableListOf("Mohan", "Kriti", "Salim") var y = mutableListOf("Sia", "Andrew") x.addAll(y) println(x) }
So, in the above code we have created a 'List' and initialised to the variable 'x'.
Below is how the values are positioned in the List,
Also we have another List that contains, 'Sia' and 'Andrew'.
Next, we have used the 'addAll()' function to add the new List 'y' that contains 'Sia' and 'Andrew' at the end of the List 'x'.
And the List 'y' is joined with 'x'.
And we get the below output,