0

I have an Optional-routine to check if I have a null-reference:

ToDo todo = new ToDo("Foo");
Optional<ToDo> candidateString = Optional.ofNullable(todo);

// Get the length of the String or 9 as a default value.
int lengthS = candidateString.map(c -> c.getId().length()).orElse(9);
System.out.println("Length of String: " + lengthS);

The ToDo-class is a simple class essentially being a container for a String, so I can force a null-reference within it:

public class ToDo {

private String id;

public ToDo() {
}

public ToDo(String id) {
    this.id = id;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

}

If I insert "Foo" as a String to the constructor, every thing works fine. If I leave it empty, I would expect the default value defined by orElse(9) to be returned. Instead I get a NullPointerException which makes the hole Optional-code pointless.

How do I make the code return the default value 9, if I leave the constuctor empty? That is, if I change the first line to:

ToDo todo = new ToDo();

Thank you for your feedback in advance

Threx

Threx
  • 73
  • 1
  • 2
  • 9
  • 1
    If you use the default constructor: `public ToDo() {}`, the id field is going to be null. In this scenario the value inside the optional is not null, so when you invoke `candidateString.map(c -> c.getId().length()` map function is going to be executed as follow: 1. c.getId() returns the id field which is null 2. null.length() throws the NullPointer – sigur Apr 14 '20 at 18:21
  • 1
    sigur beat me to it but in short: Your `ToDo` _wasn't_ null, so the `map` call still went through. But `#getId` _did_ return null. – Rogue Apr 14 '20 at 18:24

0 Answers0