Kotlin List plusElement()
Syntax & Examples
Syntax of List.plusElement()
The syntax of List.plusElement() extension function is:
fun <T> Iterable<T>.plusElement(element: T): List<T>
This plusElement() extension function of List returns a list containing all elements of the original collection and then the given element.
✐ Examples
1 Example
In this example,
- We create a list of integers named
list
containing elements1, 2, 3, 4, 5
. - We use the
plusElement()
function to add the element6
to the list. - The resulting list
newList
contains all elements of the original list plus the added element6
. - We print
newList
usingprintln()
.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5)
val newList = list.plusElement(6)
println(newList)
}
Output
[1, 2, 3, 4, 5, 6]
2 Example
In this example,
- We create a list of characters named
list
containing elements'a', 'b', 'c'
. - We use the
plusElement()
function to add the character'd'
to the list. - The resulting list
newList
contains all elements of the original list plus the added character'd'
. - We print
newList
usingprintln()
.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf('a', 'b', 'c')
val newList = list.plusElement('d')
println(newList)
}
Output
[a, b, c, d]
3 Example
In this example,
- We create a list of strings named
list
containing elements"apple", "banana", "cherry"
. - We use the
plusElement()
function to add the string"date"
to the list. - The resulting list
newList
contains all elements of the original list plus the added string"date"
. - We print
newList
usingprintln()
.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry")
val newList = list.plusElement("date")
println(newList)
}
Output
[apple, banana, cherry, date]
Summary
In this Kotlin tutorial, we learned about plusElement() extension function of List: the syntax and few working examples with output and detailed explanation for each example.