简体   繁体   中英

“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 ? extends @NonNull V in order to avoid a null check in the case where I know the remappingFunction never returns null , eg:

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM