Handle null values properly
gtrefs opened this issue · 4 comments
Following code will fail with a NullPointerException
:
final Optional<String> optional = Try.apply(() -> (String)null).toOptional();
assertThat(optional, is(equalTo(Optional.empty())));
The reason is, that the Success
type does not check whether its value is null before converting it to an Optional
:
public Optional<T> toOptional() {
return Optional.of(value);
}
I am not sure if Try
should support null values. If yes, then the following code would be a mitigation:
public Optional<T> toOptional() {
return Optional.ofNullable(value);
}
However, I did not test it. One needs to check whether there are other potential NullPointerEception
s.
I had planned to check for non nullability of parameters but I hadn't thought of using Optional.ofNullable
for this use case. Thanks. I think Try
should support null values. Of course the developer should eschew null
and replace its usage with Optional
instead. I'll add Optional.ofNullable
and check nullability of parameters ASAP.
Done and committed. I will publish it with the 0.4.0 version.
Nice 👍
Published as 0.3.1.