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 t开发者_如何转开发o 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
).
精彩评论