Kotlin List plus()
Syntax & Examples
Syntax of List.plus()
There are 4 variations for the syntax of List.plus() extension function. They are:
operator fun <T> Iterable<T>.plus(element: T): List<T>
This extension function returns a list containing all elements of the original collection and then the given element.
operator fun <T> Iterable<T>.plus( elements: Array<out T> ): List<T>
This extension function returns a list containing all elements of the original collection and then all elements of the given elements array.
operator fun <T> Iterable<T>.plus( elements: Iterable<T> ): List<T>
This extension function returns a list containing all elements of the original collection and then all elements of the given elements collection.
operator fun <T> Iterable<T>.plus( elements: Sequence<T> ): List<T>
This extension function returns a list containing all elements of the original collection and then all elements of the given elements sequence.
✐ Examples
1 Example
In this example,
- We create a list named
list1
containing the integers[1, 2, 3]
. - We use the
plus()
function to append the integer4
tolist1
. - Finally, we print the resulting list to standard output using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(1, 2, 3);
val result = list1.plus(4);
println(result);
}
Output
[1, 2, 3, 4]
2 Example
In this example,
- We create a list named
list1
containing the characters['a', 'b', 'c']
. - We use the
plus()
function to append the elements'd'
and'e'
from an array tolist1
. - Finally, we print the resulting list to standard output using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf('a', 'b', 'c');
val result = list1.plus(arrayOf('d', 'e'));
println(result);
}
Output
[a, b, c, d, e]
3 Example
In this example,
- We create a list named
list1
containing the strings['apple', 'banana']
. - We use the
plus()
function to append the strings'orange'
and'grape'
from another list tolist1
. - Finally, we print the resulting list to standard output using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("apple", "banana");
val result = list1.plus(listOf("orange", "grape"));
println(result);
}
Output
[apple, banana, orange, grape]
4 Example
In this example,
- We create a list named
list1
containing the integers[1, 2, 3]
. - We use the
plus()
function to append the integers4, 5, 6
from a sequence tolist1
. - Finally, we print the resulting list to standard output using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(1, 2, 3);
val result = list1.plus(sequenceOf(4, 5, 6));
println(result);
}
Output
[1, 2, 3, 4, 5, 6]
Summary
In this Kotlin tutorial, we learned about plus() extension function of List: the syntax and few working examples with output and detailed explanation for each example.