3 ms·
I agree with your point in general. However, in this particular case, what you wrote isn't equivalent. The explicit use of flatMap(Option.apply) in the first
by kod 12y ago
I agree with your point in general. However, in this particular case, what you wrote isn't equivalent.
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.
- whateveracct 12y agoGood 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 -.-
- ilikerps 12y agoNote that while frowned upon, such issues arise altogether more often than they should in real systems.