I want to maintain a Map
of case class
objects, such that I can add new instances and look them up by an ID.
My current (very ugly) solution (stripped down):
case class cc(i: Int)
var myccmap: Map[Int, cc] = null
def addcc(thecc: cc): cc = {
if (myccmap == null) {
myccmap = Map(thecc.hashCode, thecc)
}
else {
myccmap = myccmap ++ Map(thecc.hashCode, thecc)
}
thecc
}
And then elsewhere I can use val somecc = addcc(cc(56))
, for example, to maintain a Map
of my cc
objects added with addcc
.
This way, I can store the key, which is just the hashCode, with some data in a file, and then when I read the file, I can extract the cc
object by looking up the hashCode (which may or may not be present in myccmap
).
Is there a better way to do this, ideally without relying on a check for null
?