What are sets in Scala?
A set in Scala is a collection of unique items. We discard any repeating items when creating a set. The key point about Scala is that it includes both immutable and mutable sets. By definition, the set values contained in immutable sets cannot change. Immutable sets are the default set type used in Scala.
In order to define mutable sets, we should declare the
Scala.collection.mutablelibrary.
We can also create an empty set in Scala.
Syntax
// difference is the use of `val` and `var` to define immutable and mutable sets.
// Immutable empty set
val empty_set = Set()
// Mutable empty set
var empty_set = Set()
Immutable or mutable sets can be defined in two ways:
Method 1
// In this method, the `type` refers to the datatype of the set Int, String etc.
// Immutable set
val set1: Set[type] = Set(n1, n2, n3)
// Mutable Set
var set1: Set[type] = Set(n1, n2, n3)
Method 2
// Immutable set
val set2 = Set(n1, n2, n3)
// Mutable Set
var set2 = Set(n1, n2, n3)
Scala sets also follow the set operations
Code
Let’s look at set examples using String and Integer data:
object Main extends App {val Asia: Set[String] = Set("India", "Pakistan","Bangladesh", "Sri Lanka")val Europe = Set("England", "France", "Spain", "Germany","Belgium", "Switzerland")// Displaying Set Asiaprintln("Asia:")Asia.foreach(println)// Displaying Set Europeprintln("\nEurope:")Europe.foreach(println)// We can combine two sets using .++ method or ++ operatorval countries = Asia.++(Europe)val countries2 = Asia ++ Europe// Displaying Set Europeprintln("\nCountries using method .+:")countries.foreach(println)println("\nCountries using operator ++:")countries2.foreach(println)}
Next, let’s perform set operations with Integer Data:
object Main extends App {// Let's do it with integersval numbers1: Set[Int] = Set(12,1,23,43,14,89)val numbers2: Set[Int] = Set(1,12,89,32,21,45)// performing unionval union = numbers1.++(numbers2)println("Union: "+ union)// performing intersectionval intersection = numbers1.&(numbers2)println("intersection: "+ intersection)}
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved