Re:Databricks Scala Style Guide
by whateveracct on Tuesday March 17, 2015 @03:03PM
(#9220417)
Good point I was sloppy in my reading.
def getAddress(name: String): Option[String] = {
for {
elem <- database.get(name)
nullableAddress <- elem.data.get("address")
address <- Option(nullableAddress)
} yield address
}
def getAddress(name: String): Option[String] = {
for {
elem <- database.get(name)
address <- elem.data.get("address").flatMap(Option.apply)
} yield address
}
are both still better though.Also it seems like a bit of a strawman to use such a pathological example (null values stored in a map are frowned upon even in Java-land) to motivate the entire styleguide section about monadic chaining. They say it's contrived but still -.-
The explicit use of flatMap(Option.apply) in the first example is to deal with the case of address existing, but being a null string. Your code doesn't handle that.