chris webster wrote:I must admit I find all these, er, Options kind of confusing sometimes. I'm working on a Play prototype with ReactiveMongo and finding it difficult to know when/how to get the actual darned value out of a Future Option of Some Promise of Trying to yield Either a Success or a Failure... it sometimes feels more like Philosophy 101 than programming!
I hear ya! We have seen a couple instances where it makes sense to have a Try[Option[Something]]. One is calling a web service (we wrap the call result in a Try to indicate if the call succeeded or failed) then we wrap the successful response in an Option, indicating that the thing we're querying for may not be there. But still...that is probably the clearest it gets. I wouldn't go any further levels deep!
chris webster wrote:Still, at least it's been a while since I saw a NPE. Maybe I should create an Option of Some(NPE) just for old time's sake?
:-D
This is another topic and I'm sure I'm not telling you anything new but you can end up with Some(null) pretty easily, leading to an NPE. I've seen this directly happen using Some and passing a null value or by mapping out some hierarchy of objects and ending up with a null along the way. The first is the reason why best practice is to use "Option()" instead of "Some()" for creating an option.
Example #1 - REPL output of Some(null) causing an NPE
(^^^ That is fixed if you use "Option" everywhere that it is currently using "Some"..see below)
Example #2 - REPL Output of mapping out a hierarchy of objects where one value can return null
One way to get around the second example is to flatMap the value and explicitly wrap in option: