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
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With