# What is a better approach for operating on an arbitrary map value in Scala?

Coming from an imperative background, I have written the following code in Scala. I need to attempt to find a value in a map. If the value exists, I need to pass the value to another function and return the result, otherwise I need to return None.

def foo(index: Int): Option[FooBar] = {
val mylookup: Map[Int, String] = this.generateMap()
var out: Option[String] = None

if (mylookup.containsKey(index)) {
out = Some(mylookup(index))
} else if (mylookup.containsKey("static_value")) {
out = Some(mylookup("static_value"))
}

if (!out.getOrElse("").isEmpty) {
return this.doSomeCall(out.get).makeFooBar()
} else {
return None
}
}


I don't feel like this is the best way to accomplish this in Scala. Any ideas on how to approach this using the idiomatic nature of the language?

myLookup.get(index).orElse(myLookup.get(static_value)).map { doSomeCall(_).makeFooBar }

From the Scala doc of Option.map:
This is exactly the type of task functional programming is made for. This simple chaining of Options using map is related to the fact that Option is a monad.
• Sorry, I completely missed the part with static_value. I changed my post. – toto2 Dec 10 '13 at 22:08