Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting mutable collection to immutable

I'm looking for a best way of converting a collection.mutable.Seq[T] to collection.immutable.Seq[T].

like image 230
Nikita Volkov Avatar asked Dec 13 '11 13:12

Nikita Volkov


People also ask

How do you make a mutable list immutable?

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

Are collections in Java mutable?

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.

Is a mutable collection?

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.


2 Answers

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.

like image 37
Debilski Avatar answered Sep 22 '22 01:09

Debilski


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.

like image 138
Daniel C. Sobral Avatar answered Sep 25 '22 01:09

Daniel C. Sobral