Scala3 — Convert to and from Java collections in Scala code — scala.jdk.CollectionConverters._
Since Scala can run on the Java Virtual Machine and interoperate with java code and classes, therefore it is important to have some understanding of conversion from and to Scala and Java collections.
Just like Scala, Java also has a rich library of Collections to work with. Following are some of the Collection types in Java:
- java.util.List
- java.util.Set
- java.util.Map…
Most of Java collections map to mutable collections in Scala. Following is the mapping between collections in both programming languages:
- scala.collection.Iterable < == > java.lang.Iterable
- scala.collection.Iterator < == > java.util.Iterator
- scala.collection.mutable.Buffer < == > java.util.List
- scala.collection.mutable.Set < == > java.util.Set
- scala.collection.mutable.Map < == > java.util.Map
- scala.collection.concurrent.Map < == > java.util.concurrent.ConcurrentMap
We will discuss the scala.jdk.CollectionConverters object which deals with converting between Scala and Java collections while writing Scala code. When writing Java code, the programmer should use scala.jdk.javaapi.CollectionConverters to convert between Scala and Java collections.
Consider the following code snippet:
import scala.jdk.CollectionConverters._
val mutableScalaSet = collection.mutable.Set("one")
val javaSet = mutableScalaSet.asJava
javaSet.add("two")
mutableScalaSet //output res8: scala.collection.mutable.Set[String] = HashSet(two, one)
First we create a mutable Scala set and convert it into a java.util.Set object using .asJava method. This conversion returns an adapter for the Scala set. This means that the Scala collection is only wrapped inside a Java Set object and not actually converted; this can be confirmed when we add “two” to the javaSet object but it is also added to the mutableScalaSet object (see output).
Once created, the javaSet can be passed to any Java object which accepts a java.util.Set object for any computation.
Following conversions are also supported using asScala methods and through specially-named extension methods
scala.collection.Iterable < == > java.util.Collection (via as JavaCollection)
scala.collection.Iterator < == > java.util.Enumeration (via asJavaEnumeration)
scala.collection.mutable.Map < == > java.util.Dictionary (via asJavaDictionary)
Finally, converting from a source type to target type and back again will retrun the original source object.
For more on CollectionConverters object, please review the scaladoc @ https://www.scala-lang.org/api/3.3.1/scala/jdk/CollectionConverters$.html