Search code examples
javanullpointerexceptionoption-type

Optional ofNullable on nested reference to object


I need to check if my reference to object return null, So I use Optional like below:

return Optional.ofNullable(model.getSomeField().getUserName()).orElse("No name");

and right now, Optional return me NullPointerException because I have a null on model.getSomeField(), how to check for all of the null's in the reference that is passed in the Optional.ofNullable? For example, if model.getSomeField() is null or model.getSomeField().getUserName() is null then i want to run orElse clause.

Thanks for any help


Solution

  • Use map

    return Optional.ofNullable(model).map(Model::getSomeField).map(Field::getUserName).orElse("No name");