principleMinor
What is a better approach for operating on an arbitrary map value in Scala?
Viewed 0 times
mapwhatarbitrarybettervaluescalaoperatingforapproach
Problem
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.
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?
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?
Solution
myLookup.get(index).orElse(myLookup.get(static_value)).map { doSomeCall(_).makeFooBar }From the Scala doc of
Option.map: Returns a scala.Some containing the result of applying f to this scala.Option's value if this scala.Option is nonempty. Otherwise return None.
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.Code Snippets
myLookup.get(index).orElse(myLookup.get(static_value)).map { doSomeCall(_).makeFooBar }Context
StackExchange Code Review Q#37070, answer score: 4
Revisions (0)
No revisions yet.