The plusElement() extension function in Kotlin returns a set containing all elements of the original set and then the given element if it isn't already in this set.
The syntax of Set.plusElement() extension function is:
fun <T> Set<T>.plusElement(element: T): Set<T>
This plusElement() extension function of Set returns a set containing all elements of the original set and then the given element if it isn't already in this set.
Parameter | Optional/Required | Description |
---|---|---|
element | required | The element to be added to the set if it isn't already present. |
Set.plusElement() returns value of type Set
.
Using plusElement() to add an element to a set of integers.
For example,
fun main() {
val numbers = setOf(1, 2, 3)
val result = numbers.plusElement(4)
println(result)
}
[1, 2, 3, 4]
Using plusElement() to add an element to a set of strings.
For example,
fun main() {
val strings = setOf("one", "two", "three")
val result = strings.plusElement("four")
println(result)
}
[one, two, three, four]
Using plusElement() to add a custom object to a set of custom objects.
For example,
data class Person(val name: String, val age: Int)
fun main() {
val people = setOf(Person("Alice", 30), Person("Bob", 25))
val result = people.plusElement(Person("Charlie", 35))
println(result)
}
[Person(name=Alice, age=30), Person(name=Bob, age=25), Person(name=Charlie, age=35)]
In this Kotlin tutorial, we learned about plusElement() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.