Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala convert Option to an Int

I have looked at these links

http://blog.danielwellman.com/2008/03/using-scalas-op.html

http://blog.tmorris.net/scalaoption-cheat-sheet/

I have a map of [String, Integer] and when I do a map.get("X") I get an option. I would like the following.

val Int count = map.get(key); 
// If the key is there I would like value if it is not I want 0

How do I achieve this in one line? I need to do this several times. It looks a bit inefficient to write a function everytime for doing this. I am sure there is some intelligent one line quirk that I am missing but I really like to get the value into an integer in ONE line :)

like image 669
Kannan Ekanath Avatar asked Apr 17 '12 08:04

Kannan Ekanath


1 Answers

Just use getOrElse method:

val count: Int = map.getOrElse(key,0);

Note also, that in Scala you write type after name, not before.

like image 186
om-nom-nom Avatar answered Sep 19 '22 15:09

om-nom-nom