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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With