3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Scala Starter 101 - Convert between Mutable and Immutable

Posted at

Generally, from mutable to immutable, you use the to* series methods in mutable collections, like MutableList and ListBuffer's toList method.

In the other hand, from immutable to mutable, you can just use constructors like this: scala.collection.mutable.ListBuffer(immtableList: _*).

Note that the to* methods like toList, toMap are is performed in constant time.

Here is some examples.

Map

// from mutable to immutable
val mutableMap1 = immutableMap.toMap() // after 2.8
val mutbaleMap2 = collection.immutable.Map(x.toList: _*) // before 2.8
// from immutable to mutable
val immutableMap = scala.collection.immutable.Map(1 -> "1", 2 -> "2")
val mutableMap = scala.collection.mutable.Map(immutableMap: _*)

List

// from mutable to immutable
val immutableList = mutableListBuffer.toList
// from immutable to mutable
val immutableList = scala.collection.immutable.List(1, 2, 3)
val mutableListBuffer = scala.collection.mutable.ListBuffer(immutableList: _*)

Ref

[1] - How can I convert immutable.Map to mutable.Map in Scala?
[2] - Converting mutable to immutable map
[3] - Converting mutable collection to immutable

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?