I'm new to optionals and trying to understand why I'm receiving a null pointer exception at this line.
BottomObj bottomObj = new bottomObj();//initialized bottomObj
Optional<Location> location = Optional.ofNullable(bottomObj).map(obj -> obj.getRootObj()).map(rootObjLocation -> rootObjLocation.getLocation());
A BottomObj has a RootObj instance variable that is null in this case(as I have not set it and the constructor doesn't set it).
If I executed the line
RootObj rootObj = bottomObj.getRootObj();
I would get a null pointer exception. Thus, I'm trying to use the optional line above to deal with this scenario (ie where the bottomObj has no RootObj) to deal with the null pointer exception.
I've also tried this:
Optional<Location> location = Optional.ofNullable(bottomObj).map(obj -> obj.getRootObj()).map(rootObjLocation -> rootObjLocation.getLocation()).orElseThrow(etc...throw some exception...);
My program still crashes here every time on the getRootObj() function. Why is this happening? Shouldn't the optional deal with this?
Note, I know there are other tools I can use (such as a try catch block) to deal with this, but I'm specifically trying to understand optionals and implement the fix using their capabilities.