I'm having some confusion understanding immutable and mutable sets from Listing 3.5 in the Programming in Scala, 3rd edition book. The paragraph is telling me that it is creating immutable sets and, then updating it with +=, but then the new stored set contains all three elements. Some questions:
- How is this different from having a mutable set? Not sure I'm seeing the distinction.
- What happens to the old set that is existed before reassignment?
- Why bother calling it an immutable set if you can just reassign a new set to the
jetSet
variable?
- Is someone trolling me and altered "mutable" and "immutable" in the PDF? (Don't worry, I've also bought the actual book which will arrive soon.)
From the book:
The default way to create a set is shown in Listing 3.5:
var jetSet = Set("Boeing", "Airbus")
jetSet += "Lear"
println(jetSet.contains("Cessna"))
Listing 3.5 - Creating, initializing, and using an immutable set.
Figure 3.2 - Class hierarchy for Scala sets (not included).
In the first line of code in Listing 3.5, you define a new var named jetSet and initialize it with an immutable set containing the two strings, "Boeing" and "Airbus". As this example shows, you can create sets in Scala similarly to how you create lists and arrays: by invoking a factory method named apply on a Set companion object. In Listing 3.5, you invoke apply on the companion object for scala.collection.immutable.Set, which returns an instance of a default, immutable Set. The Scala compiler infers jetSet's type to be the immutable Set[String].
To add a new element to a set, you call + on the set, passing in the new element. On both mutable and immutable sets, the + method will create and return a new set with the element added. In Listing 3.5, you're working with an immutable set. Although mutable sets offer an actual += method, immutable sets do not.
In this case, the second line of code, "jetSet += "Lear"", is essentially a shorthand for:
jetSet = jetSet + "Lear"
Thus, in the second line of Listing 3.5, you reassign the jetSet var with a new set
containing"Boeing", "Airbus", and "Lear". Finally, the last line of Listing 3.5 prints out whether or not the set contains the string "Cessna". (As you'd expect, it prints false.)
If you want a mutable set, you'll need to use an import, as shown in Listing 3.6:
import scala.collection.mutable
val movieSet = mutable.Set("Hitch", "Poltergeist")
movieSet += "Shrek"
println(movieSet)
Thanks in advance!