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?
1 Answer 1
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 Option
s using map
is related to the fact that Option
is a monad.
-
\$\begingroup\$ That is indeed terse. However, how do I return a single value? I'll modify my code above to not be as implicit. I want to return the value from makeFooBar. \$\endgroup\$Jordan Parmer– Jordan Parmer2013年12月10日 21:44:08 +00:00Commented Dec 10, 2013 at 21:44
-
\$\begingroup\$ Ignore my last comment as I understand how that works now. However, how would I check for my static value if the index value doesn't exist? \$\endgroup\$Jordan Parmer– Jordan Parmer2013年12月10日 21:53:50 +00:00Commented Dec 10, 2013 at 21:53
-
\$\begingroup\$ Sorry, I completely missed the part with
static_value
. I changed my post. \$\endgroup\$toto2– toto22013年12月10日 22:08:44 +00:00Commented Dec 10, 2013 at 22:08