Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java <-> Scala Collection conversions, Scala 2.10 [duplicate]

Looking at the code in JavaConversions and JavaConverters, I am unsure which the "correct" way (with 2.10) to convert between Java and Scala collections (in either direction) is.

There seem to be lots of @deprecated annotations.

Has a definitive answer from the Scala Team (Typesafe?) been published?

Thanks, John

like image 778
John Smith Avatar asked Jul 26 '12 22:07

John Smith


2 Answers

This is the poster child example for the dangers of import JavaConversions._:

scala> val m = Map(1 -> "one")
m: scala.collection.immutable.Map[Int,String] = Map(1 -> one)

scala> m.contains(1)
res0: Boolean = true

scala> m.contains("")
<console>:9: error: type mismatch;
 found   : String("")
 required: Int
              m.contains("")
                         ^

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

scala> m.contains("")
res2: Boolean = false

Instead of issuing a type error, the compiler converts the Scala Map to to a java.util.Map, which has a looser signature that accepts Object.

like image 129
retronym Avatar answered Oct 11 '22 08:10

retronym


I don't know of any such proclamation, but you should just always use JavaConverters, i.e. the ones that require you to indicate conversions with .asScala and .asJava.

As I understand it, JavaConverters were brought in in 2.8.1 because the JavaConversions in 2.8 were dangerous and made it easy to accidentally convert things where you weren't expecting it.

like image 45
Luigi Plinge Avatar answered Oct 11 '22 08:10

Luigi Plinge