With this simple code
import scala.collection.JavaConversions._
new java.util.concurrent.ConcurrentHashMap[String,String] ().toMap.put("abc","def")
Scala throw a java.lang.UnsupportedOperationException.
Why ?
Well this is what happens (I think):
new java.util.concurrent.ConcurrentHashMap[String,String]()
toMap
toMapis not defined on java.util.concurrent.ConcurrentHashMap an implicit conversion to a mutable scala map is applied. And toMap then makes of this mutable Map an immutable Map.scala.collection.immutable.Map.scala.collection.immutable.Map to java.util.Map in your import import scala.collection.JavaConversions._ which has a put(...) method defined. However, the conversion returns a wrapper extending AbstractMap.put(...) method implemented in that wrapper. Therefore, the call ends up in the default implementation of java.util.AbstractMap which does not really implement put(...) but instead throws an UnsupportedOperationException
I guess the confusion caused by this, is one reason most scala developers prefer import scala.collection.JavaConverters._ over import scala.collection.JavaConversions._ nowadays.
So, I think, this might be what you want to do:
import scala.collection.JavaConverters._
new java.util.concurrent.ConcurrentHashMap[String,String]().asScala.put("abc","def")
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