w3resource

Scala Set: Creating an empty set and adding elements

Scala Set Exercise-1 with Solution

Write a Scala program to create an empty set and add elements to it.

Sample Solution:

Scala Code:

object EmptySetExample {
  def main(args: Array[String]): Unit = {
    // Create an empty set
    var nums_set = Set.empty[Int]

    // Add elements to the set
    nums_set += 10
    nums_set += 20
    nums_set += 30
    nums_set += 40
    nums_set += 50
    
    // Print the set
    println("Set elements: " + nums_set)
  }
}

Sample Output:

Set elements: HashSet(10, 20, 50, 40, 30)

Explanation:

In the above exercise,

  • First, we create an empty set nums_setusing the Set.empty[Int] syntax. The Int specifies the type of elements that the set will contain.
  • We then add elements to the set using the += operator. In this example, we add the integers 10, 20, 30, 40 and 50 to the set.
  • Finally, we print the elements of the set using string concatenation and the println function.

Scala Code Editor :

Previous: Scala Sets Exercises Home.
Next: Creating sets and finding the union of two sets.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.