javaoptional-chaining

Using Optionals in Java 11 to avoid null pointer exceptions using functional chaining


I would like to use Java 11's Optional to protect myself from the dreaded null pointer exception. I wrote a basic test to check my understanding of how they work. like. so

   @Test
   public void optionalsWorkingAsExpected() {
       String x = null;
       var y = Optional.ofNullable(x.toString().toLowerCase()).orElse(null);
       assertThat(y).isNull();
   }

However this test failed with yet another null pointer exception saying

Cannot invoke "String.toString()" because "x" is null

For context what I want to be able to do is use a function chain like this:

myClass.getMyData().transformData().getName()

any of these function calls could result in being null and they are chained. I don't really care which one is null in the chain but if any of them is I want to return null to my variable. like so

String name = Optional.ofNullable(myClass.getMyData.transformMyData.getName()).orElse(null);

Any suggestions?


Solution

  • I think happy-songs comment and link to a solution is the right direction. You'll want something like this to pass your test.

    Optional.ofNullable(x).map(Object::toString).map(String::toLowerCase).orElse(null);