oxbow_lakes
oxbow_lakes

Reputation: 134260

Scala do I have to convert to a Seq when creating a collection from an iterable?

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)?

Upvotes: 5

Views: 2162

Answers (2)

Szymon Jachim
Szymon Jachim

Reputation: 575

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()

Upvotes: 0

Germán
Germán

Reputation: 4565

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.

Upvotes: 3

Related Questions