lundi 2 mars 2015

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?




Aucun commentaire:

Enregistrer un commentaire