Consider a method such as ConcurrentHashMap
's compute
method:
public V compute(
K key,
BiFunction<? super K,? super V,? extends V> remappingFunction)
I would like to annotate this for nullability checking with checker framework:
public @Nullable V compute(
K key,
BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> remappingFunction);
but this isn't quite right: I would like to be able to infer that it returns ? extends @NonNull V
in order to avoid a null check in the case where I know the remappingFunction
never returns null
, e.g.:
@NonNull V value = map.compute(key, (k, v) -> {
if (v == null) {
return new V();
}
v.increment();
return v;
});
Is it possible to express that?
The Checker Framework provides two ways to write conditional specifications, where a type depends on other values or types.
@PolyNull
indicates that two types must be the same, but their common type could be either @NonNull
or @Nullable
. It looks like this will enable you to express the desired specification.@EnsuresNonNullIf
makes a type depend on a method's return value.Both of these are described in section Nullness Annotations in the Checker Framework Manual.
PS: Once you have an improved specification, you can submit it as a pull request to update the annotated JDK that is shipped with the Checker Framework.