Skip to content

Not-null varargs argument with Nullable elements - considered as Nullable #674

@kbarczynski-rtbh

Description

@kbarczynski-rtbh
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE_USE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER,
        ElementType.LOCAL_VARIABLE })
public @interface Nullable {
}
--------------------------------------------------------------------------
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE_USE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER,
        ElementType.LOCAL_VARIABLE })
public @interface NonNull {
}
--------------------------------------------------------------------------
protected static String composeName(@Nullable String @NonNull... names) {
    StringJoiner stringJoiner = new StringJoiner(":");
    for (String name : names) {
        if (name != null && !name.isEmpty()) {
            stringJoiner.add(name);
        }
    }
    return stringJoiner.toString();
}

result:

error: [NullAway] enhanced-for expression names is @Nullable

which points to line:

for (String name : names) {

Key facts:

  • names is vararg array, it's expected to be not-null and contain:
  • Nullable String elements
  • For some reason these two annotations are mixed.

Nice examples:
https://help.eclipse.org/latest/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftask-using_null_type_annotations.htm&cp=1_3_9_1_3&anchor=compatibility

There is also one answer I found helpful:
https://stackoverflow.com/questions/32327134/where-does-a-nullable-annotation-refer-to-in-case-of-a-varargs-parameter

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugjspecifyRelated to support for jspecify standard (see jspecify.dev)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions