Scala convert Option to an Int

scala, scala-collections

Solution

Just use getOrElse method:

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

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

Problem

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

Original source