Reputation: 1788
Suppose I have a method to parse a number and whose return value nullability contract should be inferred from its argument:
@...
public static Integer tryParse(@Nullable final String in, @... final Integer defaultValue) {
if ( in == null ) {
return defaultValue;
}
@Nullable
final Integer out = Ints.tryParse(in); // from Google Guava, does not accept nulls
if ( out == null ) {
return defaultValue;
}
return out;
}
where the @...
marks stand for some nullability transition. Having that, I'd also have something like:
final int n = tryParse("foo", 0)
(safe in all cases: the n
is considered never to have null
so unboxing won't cause NullPointerException
)@Nullable final Integer n = tryParse("foo", null)
(safe: both hands are null-aware)final int n = tryParse(someVar, null)
(unsafe: may cause an NPE if someVar
is not a valid int string representation).Is there a way to bind the returned value nullability depending on the argument passed to the method parameter nullability, or should I just create an overload with clearly segregated boxed and primitive default values (this might be fine for this case, but primitive types are not the only situation I'd like to handle)?
If it matters: I don't use static analysis tools in my build, but I use the nullability inspections in IntelliJ IDEA (javax.annotation
, not org.jetbrains.annotations
) with the warning severity set.
Upvotes: 1
Views: 92