Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use Scala options to avoid the following NoSuchElementException?

Tags:

scala

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?

like image 798
deltanovember Avatar asked Aug 15 '11 22:08

deltanovember


1 Answers

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

like image 64
tenshi Avatar answered Oct 28 '22 23:10

tenshi