Kotlin Set plusElement()
Syntax & Examples


Set.plusElement() extension function

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.


Syntax of Set.plusElement()

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.

Parameters

ParameterOptional/RequiredDescription
elementrequiredThe element to be added to the set if it isn't already present.

Return Type

Set.plusElement() returns value of type Set.



✐ Examples

1 Adding an element to a set of integers

Using plusElement() to add an element to a set of integers.

For example,

  1. Create a set of integers.
  2. Use plusElement() to add an element to the set.
  3. Print the resulting set.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3)
    val result = numbers.plusElement(4)
    println(result)
}

Output

[1, 2, 3, 4]

2 Adding an element to a set of strings

Using plusElement() to add an element to a set of strings.

For example,

  1. Create a set of strings.
  2. Use plusElement() to add an element to the set.
  3. Print the resulting set.

Kotlin Program

fun main() {
    val strings = setOf("one", "two", "three")
    val result = strings.plusElement("four")
    println(result)
}

Output

[one, two, three, four]

3 Adding a custom object to a set of custom objects

Using plusElement() to add a custom object to a set of custom objects.

For example,

  1. Create a data class.
  2. Create a set of custom objects.
  3. Use plusElement() to add a new custom object to the set.
  4. Print the resulting set.

Kotlin Program

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

Output

[Person(name=Alice, age=30), Person(name=Bob, age=25), Person(name=Charlie, age=35)]

Summary

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.