Skip to content

Instantly share code, notes, and snippets.

@tomaszperek
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomaszperek/6b10b81514d256899b3f to your computer and use it in GitHub Desktop.
Save tomaszperek/6b10b81514d256899b3f to your computer and use it in GitHub Desktop.
//proper way to wrap calls to java apis
val map = new java.util.HashMap[String, String]()
map.put("key1", "value1")
val maybeValue1 = Option(map.get("key1")) //Some("value1")
val maybeValue2 = Option(map.get("key2")) //None
//equivalent of "if(x != null && condition(x))"
val optionX: Option[T] = Option(x)
optionX.exists(condition)
//equivalent of "if(x == null || condition(x))"
optionX.forall(condition)
//equivalent of "if(x != null && condition(x)) f(x)"
optionX.filter(condition).map(f)
// map and flat map example:
val x = Some(Map("a" -> "some value"))
x.flatMap(_.get("a")).map(_.toUpperCase) // Some("SOME VALUE")
x.flatMap(_.get("b")).map(_.toUpperCase) // None - notice how nice
//the lack of value for given key in map is handled
//options with for-comprehension
for {
a <- Some(1)
b <- Some(2)
} yield a + b // Some(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment