views:

438

answers:

2

Perhaps I am barking up the wrong tree (again) but if it is normal practice to have a property typed as a scala.collection.immutable.Set[A], then how would you create one of these given a scala.Iterable[A]? For example:

class ScalaClass {
    private var s: scala.collection.immutable.Set[String]

    def init(): Unit = {
        val i = new scala.collection.mutable.HashSet[String] 
        //ADD SOME STUFF TO i

        s = scala.collection.immutable.Set(i) //DOESN'T WORK

        s = scala.collection.immutable.Set(i toSeq : _ *) //THIS WORKS
    }
}

Can someone explain why it is necessary to create the immutable set via a Seq (or if it is not, then how do I do it)?

+3  A: 

Basically because you're creating the immutable Set through the "canonical factory method" apply in Set's companion object, which takes a sequence, or "varargs" (as in Set(a,b,c)). See this:
http://scala-tools.org/scaladocs/scala-library/2.7.1/scala/collection/immutable/Set$object.html

I don't think there is another to do it in the standard library.

Germán
A: 

It will make an immutable copy:

scala> val mu = new scala.collection.mutable.HashSet[String]
mu: scala.collection.mutable.HashSet[String] = Set()

scala> val im = mu.clone.readOnly
im: scala.collection.Set[String] = ro-Set()
Szymon Jachim
I'm sorry, I don't really understand your point. My question was why it wasn't easier to convert from an Iterable to an immutable Collection (except via a Seq). Obviously you've given me a read-only collection; not an immutable one
oxbow_lakes
Yes it is read-only... Isn't it a synonym of immutable? Maybe not always... but in this case? Do you know of a way to mutate this collection? This is the only interface to it and it is read only. There's no way it will ever change.
Szymon Jachim