Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle Hashtable nulls in Scala?

I'm porting some java code across and have the following

val overnightChanges: java.util.Hashtable[String, Double] = ...

When I try

if (null != overnightChanges.get(...))

I get the following warning

warning: comparing values of types Null and Double using `!=' will always yield true

like image 679
deltanovember Avatar asked Dec 02 '22 02:12

deltanovember


1 Answers

Primitive and reference types are much less different in scala than they are in java, and so the convention is that name starts with an uppercase for all of them. Double is scala.Double which is the primitive java double, not the reference java.lang.Double.

When you need "a double or no value" in scala, you would use Option[Double] most of the time. Option has strong library support, and the type system will not let you ignore that there might be no value. However, when you need to interact closely with java, as in your example, your table does contain java.lang.Double and you should say it so.

val a = new java.util.HashMap[String, java.lang.Double]

If java.lang.Double starts to appear everywhere in your code, you can alias to JDouble, either by importing

import java.lang.{Double => JDouble}

or by defining

type JDouble = java.lang.Double 

There are implicit conversions between scala.Double and java.lang.Double, so interaction should be reasonably smooth. However, java.lang.Double should probably be confined to the scala/java interaction layer, it would be confusing to have it go deep into scala code.

like image 84
Didier Dupont Avatar answered Dec 05 '22 04:12

Didier Dupont