Java interoperability

As we mentioned earlier, Scala has very rich collection API. The same applies for Java but there are lots of differences between the two collection APIs. For example, both APIs have iterable, iterators, maps, sets, and sequences. But Scala has advantages; it pays more attention to immutable collections and provides more operations for you in order to produce another collection. Sometimes, you want to use or access Java collections or vice versa.

JavaConversions is no longer a sound choice. JavaConverters makes the conversion between Scala and Java collection explicit and you'll be much less likely to experience implicit conversions you didn't intend to use.

As a matter of fact, it's quite trivial to do so because Scala offers in an implicit way to convert between both APIs in the JavaConversion object. So, you might find bidirectional conversions for the following types:

Iterator               <=>     java.util.Iterator
Iterator <=> java.util.Enumeration
Iterable <=> java.lang.Iterable
Iterable <=> java.util.Collection
mutable.Buffer <=> java.util.List
mutable.Set <=> java.util.Set
mutable.Map <=> java.util.Map
mutable.ConcurrentMap <=> java.util.concurrent.ConcurrentMap

In order to be able to use these kinds of conversion, you need to import them from the JavaConversions object. For example:

scala> import collection.JavaConversions._
import collection.JavaConversions._

By this, you have automatic conversions between Scala collections and their corresponding in Java:

scala> import collection.mutable._
import collection.mutable._
scala> val jAB: java.util.List[Int] = ArrayBuffer(3,5,7)
jAB: java.util.List[Int] = [3, 5, 7]
scala> val sAB: Seq[Int] = jAB
sAB: scala.collection.mutable.Seq[Int] = ArrayBuffer(3, 5, 7)
scala> val jM: java.util.Map[String, Int] = HashMap("Dublin" -> 2, "London" -> 8)
jM: java.util.Map[String,Int] = {Dublin=2, London=8}

You can also try to convert other Scala collections into Java ones. For example:

Seq           =>    java.util.List
mutable.Seq => java.utl.List
Set => java.util.Set
Map => java.util.Map

Java doesn't provide the functionality to distinguish between immutable and mutable collections. The List will be java.util.List where all attempts to mutate its elements will throw an Exception. The following is an example to demonstrate this:

scala> val jList: java.util.List[Int] = List(3,5,7)
jList: java.util.List[Int] = [3, 5, 7]
scala> jList.add(9)
java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
... 33 elided

In Chapter 2, Object-Oriented Scala, we briefly discussed using implicits. However, we will provide a detailed discussion on using implicits in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.110.0