Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala type conversion error, need help!

Tags:

scala

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

like image 891
Mansoor Ashraf Avatar asked Jun 08 '10 15:06

Mansoor Ashraf


1 Answers

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)
like image 70
Abhinav Sarkar Avatar answered Sep 28 '22 01:09

Abhinav Sarkar