44

It appears the toSeq method in Scala collections returns a scala.collection.Seq, I could also return a Traversable or Iterable but need to convert this to a scala.collection.immutable.Seq.

Is there an easy way to do this?

Thanks Richard

0

1 Answer 1

78

Use the to method to convert between arbitrary collection types in Scala 2.10:

scala> Array(1, 2, 3).toSeq
res0: Seq[Int] = WrappedArray(1, 2, 3)

scala> Array(1, 2, 3).to[collection.immutable.Seq]
res1: scala.collection.immutable.Seq[Int] = Vector(1, 2, 3)
4
  • 1
    Your answer helped me, but WHY, oh why is this even needed? I'm only working with immutable collections - how come a result of for-yield would need such a .to?
    – akauppi
    Commented Jun 14, 2016 at 7:14
  • 2
    My friend, Ivan Yurchenko clarified this: The problem is that there are three things: A) scala.collection.Seq B) scala.collection.immutable.Seq C) scala.collection.mutable.Seq B and C derive from A so, if we have A, we can't surely say if it's mutable or immutable, that's why explicit conversion (.toList or something) or setting them immutable from the beginning is needed
    – akauppi
    Commented Jun 14, 2016 at 8:20
  • 1
    It's just weird because the default Seq in Scala is just collections.Seq; which is odd because mostly, everything is immutable. List(1,2,3).toSeq generates a collections.Seq... not immutable.collections.Seq. Doesn't that seem wrong?
    – PlexQ
    Commented May 30, 2018 at 5:42
  • and even more weirdly - a immutable.collections.Seq .toIterable yields a collections.Iterable, NOT a immutable.collections.Iterable!
    – PlexQ
    Commented May 30, 2018 at 5:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.