Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional Type returns a null value

I have a class like this.

public class SomeClass {

  private Optional<String> testString;

  public SomeClass() { 
      populateFields();
  }

  public Optional<String> getTestString() {
      return testString;
  }

  private void populateFields() {
     if(//something is going false here){
       testString = functionThatReturnsOptionalString();
     }
  }

}

Now instanceOfSomeClass.getTestString() returns null. Isn't Optional always supposed to contain a non-null value or be empty? I am trying or avoid isNull() and just use isEmpty() in my caller.

If I put a breakpoint on the first line of populateFields() and check the value in testString at that time, it shows the value as null. Meaning the default value for this field(before being assigned anything) is null.

Please shed light on this situation; and maybe the correct usage of Optional?

like image 516
Gadam Avatar asked Mar 02 '26 22:03

Gadam


2 Answers

An Optional always contains a non-null value or is empty, yes, but you don't have an Optional, you have a reference of type Optional pointing to null. You need to initialize testString, e.g. to Optional.empty().

Optional isn't magic, it's an object like any other, and the Optional reference itself can be null. It's the contents of the Optional that can't be null.

like image 135
Louis Wasserman Avatar answered Mar 05 '26 11:03

Louis Wasserman


From the oracle documentation for the Optional type :

A container object which may or may not contain a non-null value.

So, yes it will return null if the variable is set to null. More info here

like image 33
Samuel Rondeau-Millaire Avatar answered Mar 05 '26 12:03

Samuel Rondeau-Millaire