I’m reading the Programming in Scala book by the Scala Creator and I’m a bit confuse on the example of Set.
Here it is for Immutable Set:
var jetSet = Set("Boeing", "Airbus")
jetSet += "Lear"
println(jetSet.contains("Cessna"))
What’s the point of this?
The set is immutable but the variable jetSet is mutable.
1) So every time I add to the set with += it creates a new set? So the variable point to a new set in memory?
2) Shouldn’t it be:
val jetSet = set("cow","sheep","duck") ? Why does it have to be a var? Is there a reason to use var for a immutable set?
The advantage of immutable data structures, in this case Set, is that they are persistent. For example:
Immutability of these Set objects makes it easier to reason about the program because updates to the
jetSet1variable don’t have side effects in other parts of the code (in this case, whereverjetSet2is used). Although it’s not clear from this example, there are occasions when it’s convenient to store immutable values in mutablevarreferences; most often, thevarwill have a limited scope (e.g., local to a function).Immutable data structures often have clever implementations that are quite efficient. Unfortunately, the Scala collection API is not well documented regarding performance, but I would expect most operations to be roughly O(log N) time. For example, given a large immutable Set
s, one should be able to efficiently constructs + x, a new Set with an extra element. Of course, immutability guarantees thatsis also preserved. Under the hood,sands+xwill be stored using some kind of tree data-structures with shared components.The title of your question suggest you are also looking for advice about using
valorvar. The rule of thumb is to usevalwhenever you can conveniently. If avaris necessary, then try to limit the variable’s scope as much as possible.