In this tutorial, you shall learn how to add an element to a given Set in Kotlin using MutableSet.add() function, with examples.

Kotlin – Add Element to Set

To add an element to a Set in Kotlin, call add() function on this Mutable Set and pass the element to add to add() function.

add() function is available for MutableSet, but not for Set.

MutableSet.add() function adds the given element to this Set and returns a boolean value. If adding the element to this Set is successful, the function returns true, or else it returns false.

Examples

ADVERTISEMENT

1. Set.add() – Add element to Mutable Set

In the following example, we will create a Set of Integers, and use add() function of the Set class to add elements to this Set.

Main.kt

fun main(args: Array<String>) {
    var mySet = mutableSetOf(1, 4, 9, 16, 25)
    println("Original Set : ${mySet}")
    mySet.add(36)
    mySet.add(49)
    println("Modified Set : ${mySet}")
}

Output

Original Set : [1, 4, 9, 16, 25]
Modified Set : [1, 4, 9, 16, 25, 36, 49]

2. Add an element that is already present in the set

Now, let us try to add element 9 to the Set mySet. Since the element is already present in the Set, add() returns false, and the Set remains unchanged.

Main.kt

fun main(args: Array<String>) {
    var mySet = mutableSetOf(1, 4, 9, 16, 25)
    if( mySet.add(9) ) {
        println("Element added to Set successfully.")
    } else {
        println("The element is already present in the Set.")
    }
}

Output

The element is already present in the Set.

We may try adding elements that are present or not present and verify the result.

Conclusion

In this Kotlin Tutorial, we learned how to add elements to a mutable Set, with the help of examples.