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?

\$\endgroup\$
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.

\$\endgroup\$
  • \$\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 Dec 10 '13 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 Dec 10 '13 at 21:53
  • \$\begingroup\$ Sorry, I completely missed the part with static_value. I changed my post. \$\endgroup\$ – toto2 Dec 10 '13 at 22:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.