I am getting a weird error when trying to use a Java map in Scala. This is the snippet of code
val value:Double = map.get(name)
if (value eq null) map.put(name, time) else map.put(name, value + time)
the map is defined as
val map=new ConcurrentHashMap[String,Double]
and this is the error I am getting
error: type mismatch;
found : Double
required: ?{val eq: ?}
Note that implicit conversions are not applicable because they are ambiguous:
both method double2Double in object Predef of type (Double)java.lang.Double
and method doubleWrapper in object Predef of type (Double)scala.runtime.RichDouble
are possible conversion functions from Double to ?{val eq: ?}
if (value eq null) map.put(name, time)
I am new to Scala so I am having a hard time parsing the stacktrace. Any help would be appreciated
First, map.get(name)
will not return null
in the case when name
key is not present in the map. It will instead return a Double(0.0)
.
Second, the error that you see is because scala is trying to implicitly convert the returned Double value to a type suitable for the eq
comparision and it finds more than one implicit conversions in the scope.
The better way to do what you are doing is
if (map contains name) map.put(name, map.get(name) + time)
else map.put(name, time)
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