How to handle Hashtable values ​​in Scala?

I am porting several java codes 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 Null and Double values ​​with `! = 'will always give true

+4
source share
3 answers

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

If you need a “double or no value” in scala, you would most often use Option[Double] . The variant has strong library support, and the type system will not let you ignore that there can be no value. However, when you need to work closely with java, as in your example, your table contains java.lang.Double, and you have to say that.

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

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

 import java.lang.{Double => JDouble} 

or defining

 type JDouble = java.lang.Double 

There are implicit conversions between scala.Double and java.lang.Double , so the interaction should be smooth enough. However, java.lang.Double should probably be limited to the scala / java interaction layer, it would be difficult to inject it into scala code.

+14
source

In Scala, Binary primitives and therefore cannot be null. This is annoying when using java cards directly, because when the key is not defined, you get a standard default value (here 0.0):

 scala> val a = new java.util.Hashtable[String,Double]() a: java.util.Hashtable[String,Double] = {} scala> a.get("Foo") res9: Double = 0.0 

If the value is an object of type String or List, your code should work as expected.

So, to solve the problem, you can:

  • Use contains in the if condition.
  • Use one of the Scala maps (many conversions are defined in scala.collection.JavaConversions )
+5
source

Use Scala “options”, also known as “possible” in Haskell:

http://blog.danielwellman.com/2008/03/using-scalas-op.html

0
source

All Articles