Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pluselement
mutablelist
kotlin
communitycreator

How to use the plusElement() method of MutableList in Kotlin

Programming Bytes

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")

}
Using the plusElement() method

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].

RELATED TAGS

pluselement
mutablelist
kotlin
communitycreator
RELATED COURSES

View all Courses

Keep Exploring