开发者

Can I use Scala options to avoid the following NoSuchElementException?

开发者 https://www.devze.com 2023-03-28 02:37 出处:网络
I have the following HashMap val lastAsk = new HashMap[String, Quote] Quote objects have a price() method

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).

0

精彩评论

暂无评论...
验证码 换一张
取 消