How to use the plusElement() method of MutableList in Kotlin
Overview
The plusElement() method creates a new List by combining the current MutableList and the passed element.
Syntax
fun <T> Iterable<T>.plusElement(element: T): List<T>
Parameter
This method takes the element to be added as an argument.
Return value
This method returns a new MutableList created by combining the invoking MutableList and the passed element.
Code
The code below demonstrates how to use the plusElement() method in Kotlin:
fun main() {val list: List<Int> = mutableListOf(1, 2, 3, 4)println("The list is : $list")val newList = list.plusElement(5);// [list elements + 5]println("list.plusElement(5) : $newList")}
Explanation
In the above code:
- Line 3: We create a new
MutableListobject with namelistusing themutableListOf()method. For themutableListOf()method, we provide1,2,3,4as an argument. All the provided arguments are present in the returnedlist. The list is[1,2,3,4]. - Line 6: We use the
plusElement()method with5as an argument. This creates and returns a newListby combining the elements of thelistvariable and5. The returned list is[1,2,3,4,5].