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.

Using the plusElement()

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 MutableList object with name list using the mutableListOf() method. For the mutableListOf() method, we provide 1,2,3,4 as an argument. All the provided arguments are present in the returned list. The list is [1,2,3,4].
  • Line 6: We use the plusElement() method with 5 as an argument. This creates and returns a new List by combining the elements of the list variable and 5. The returned list is [1,2,3,4,5].
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources