I'm looking for a best way of converting a collection.mutable.Seq[T]
to collection.immutable.Seq[T]
.
Java offers List. copyOf to convert a mutable list to an immutable one (copying it if needed), but offers no method that inverts this logic (creating a mutable List only if the input isn't mutable already).
If you're wondering about java. util. ArrayList - it is mutable and it is not creating another List instance on add() or remove() . If you are looking for immutable list - check Guava implementation of ImmutableList or Collections.
A mutable collection can be updated or extended in place. This means you can change, add, or remove elements of a collection as a side effect. Immutable collections, by contrast, never change.
As specified:
def convert[T](sq: collection.mutable.Seq[T]): collection.immutable.Seq[T] = collection.immutable.Seq[T](sq:_*)
Addition
The native methods are a little tricky to use. They are already defined on scala.collection.Seq
and you’ll have to take a close look whether they return a collection.immutable
or a collection.mutable
. For example .toSeq
returns a collection.Seq
which makes no guarantees about mutability. .toIndexedSeq
however, returns a collection.immutable.IndexedSeq
so it seems to be fine to use. I’m not sure though, if this is really the intended behaviour as there is also a collection.mutable.IndexedSeq
.
The safest approach would be to convert it manually to the intended collection as shown above. When using a native conversion, I think it is best practice to add a type annotation including (mutable
/immutable
) to ensure the correct collection is returned.
If you want to convert ListBuffer
into a List
, use .toList
. I mention this because that particular conversion is performed in constant time. Note, though, that any further use of the ListBuffer
will result in its contents being copied first.
Otherwise, you can do collection.immutable.Seq(xs: _*)
, assuming xs is mutable, as you are unlikely to get better performance any other way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With