I'm in the process of learning Scala, and I have to say that I'm really enjoying it. I'm porting to Scala a previous Java project of mine, trying to take advantage of the language when I can/know how to (mainly pattern matching and trying to use vals, not into recursion or functions yet).
In the java project, I had an HashMap
that started as empty and would get filled by using some methods. Then, of course, I'd use hmap.get(key)
to retrieve the objects.
I'd like to use an immutable HashMap
this time, but I'm kind of struggling with it! Here's my code:
val recipes = new HashMap[String,Any]()
private def addCrucibleRecipe(tag: String, tagAddon: String, result: ItemStack, cat: Any, aspects: AspectList) {
val recipe = new CrucibleRecipe(some params)
if(recipe.isInstanceOf[CrucibleRecipe]) recipes + (tag -> recipe)
else throw new IllegalArgumentException(tag + " is not a valid recipe!")
}
As you can see, I'm using the +
operator, which should return a new HashMap
with the previous values and the new one in its tail.
When I call recipes.get(key)
, however, the list contains Option None
.
This means i'm still pointing the old, empty HashMap
.
How the hell can I update the reference? And maybe that may sound dumb but I'm really new to functional programming. How is it better than a mutable one?
And if there's an even more functional or efficient way to do this in Scala please tell me, I'm eager to learn :)