I have the following HashMap
val lastAsk = new HashMap[String, Quote]
Quote objects have a price() method
The following
lastAsk(lastSecurity).price
throws NoSuchElementException if lastSecurity is not a key. To fix I could use contains to check then return -1 if the key is not found. However this feels like a hack can I use Option here to engineer a more elegant solution?
Map has method
getthat returnsOption, so you can write something like this:You can either use option further in your code or provide some default with the help of option’s method
getOrElse(in my example it’s0).