Coming from a Java
background, I'm used to the common practice of dealing with collections: obviously there would be exceptions but usually code would look like:
public class MyClass {
private Set<String> mySet;
public void init() {
Set<String> s = new LinkedHashSet<String>();
s.add("Hello");
s.add("World");
mySet = Collections.unmodifiableSet(s);
}
}
I have to confess that I'm a bit befuddled by the plethora of options in Scala. There is:
scala.List
(andSeq
)scala.collections.Set
(andMap
)scala.collection.immutable.Set
(andMap
,Stack
but notList
)scala.collection.mutable.Set
(andMap
,Buffer
but notList
)scala.collection.jcl
So questions!
- Why are
List
andSeq
defined in packagescala
and notscala.collection
(even though implementations ofSeq
are in the collection sub-packages)? - What is the standard mechanism for initializing a collection and then freezing it (which in Java is achieved by wrapping in an
unmodifiable
)? - Why are some collection types (e.g.
MultiMap
) only defined as mutable? (There is no immutableMultiMap
)?
I've read Daniel Spiewak's excellent series on scala collections and am still puzzled by how one would actually use them in practice. The following seems slightly unwieldy due to the enforced full package declarations:
class MyScala {
var mySet: scala.collection.Set[String] = null
def init(): Unit = {
val s = scala.collection.mutable.Set.empty[String]
s + "Hello"
s + "World"
mySet = scala.collection.immutable.Set(s : _ *)
}
}
Although arguably this is more correct than the Java version as the immutable collection cannot change (as in the Java case, where the underlying collection could be altered underneath the unmodifiable
wrapper)