javachecker-framework

"NonNull if the function returns non-null"?


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?


Solution

  • The Checker Framework provides two ways to write conditional specifications, where a type depends on other values or types.

    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.