My code is as follows
import scala.collection.mutable.HashMap
type CrossingInterval = (Date, Date)
val crossingMap = new HashMap[String, CrossingInterval]
val crossingData: String = ...
Firstly why does the following line compile?
val time = crossingMap.getOrElse(crossingData, -1)
I would have thought -1 would have been an invalid value
Secondly how do I do a basic check such as the following
if (value exists in map) {
}
else {
}
In Java I would just check for null values. I’m not sure about the proper way to do it in Scala
Typing your code in the interpreter shows why the first statement compiles:
Basically,
getOrElseon aMap[A, B](hereB = CrossingDate) accepts a parameter of any typeB1 >: B: that means thatB1must be a supertype ofB. HereB1 = Any, and -1 is of course a valid value of typeAny. In this case you actually want to have a type declaration fortime.For testing whether a key belongs to the map, just call the contains method. An example is below – since Date was not available, I simply defined it as an alias to String.
If you want to check whether a value is part of the map, the simplest way is to write this code:
However, this builds a
Setcontaining all values. EDIT: You can find a better solution for this subproblem in Kipton Barros comment.