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 get
that returns Option
, so you can write something like this:
lastAsk get lastSecurity map (_ price) getOrElse 0
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's 0
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With