4
\$\begingroup\$

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?

asked Dec 10, 2013 at 20:21
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$
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.

answered Dec 10, 2013 at 21:27
\$\endgroup\$
3
  • \$\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\$ Commented 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\$ Commented Dec 10, 2013 at 21:53
  • \$\begingroup\$ Sorry, I completely missed the part with static_value. I changed my post. \$\endgroup\$ Commented Dec 10, 2013 at 22:08

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.