Last active
August 29, 2015 14:22
-
-
Save tomaszperek/6b10b81514d256899b3f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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