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
toMap
is 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")
scala.collection.Map
to java.util.Map
. But it actually returns a wrapper extending AbstractMap
which delegates methods like get
to corresponding scala.collection.Map
methods. And there is no method corresponding to put
, so it isn't overridden and AbstractMap
's implementation is inherited.
Commented
Jul 25, 2016 at 13:58
Unlike Java, the default collections in Scala are immutable. If you take a look at the api for Map
(found here) you'll see that Map
lacks a method put
. So the exception is telling you, quite rightly, that Map
can't do what you want it to do. If you want to fill the Map
with values:
Map("abc" -> "def")
By the way, an immutable collection is already thread-safe. No need to use a ConcurrentHashMap
.
toMap
do? ConcurrentHashMap is already a map. I guess,new java.util.concurrent.ConcurrentHashMap[String,String] ().put("abc","def")
should work fine.