Super type of List<@Nullable Something> and List<@NonNull Something>

39 views
Skip to first unread message

William Shackleford

unread,
Jun 29, 2021, 10:01:03 AM6/29/21
to Checker Framework discussion

Let's say one has a method that only reads from a list and when  it gets something from
the list it checks that it is not null before using it.

It is therefore safe to call this method with a List<@Nullable Something> since it is guaranteed not to throw an exception even if there are nulls on the list. It is also safe to call
with List<@NonNull Something> since it will never put a null value onto the list.

Do I have to create two methods with identical content to handle both cases or is
there a way to effectively declare the method to take a parameter which is the super type of both?


Michael Ernst

unread,
Jun 29, 2021, 10:26:15 AM6/29/21
to William Shackleford, Checker Framework discussion
You can write a single method.  Two mechanisms that you could use are Java wildcards and type qualifier polymorphism.  Both are described in chapter 30, "Generics and polymorphism", in the manual (https://checkerframework.org/manual/#polymorphism).

Below is a code example showing both approaches.

                    -Mike

   
import org.checkerframework.checker.nullness.qual.PolyNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.List;

public class Foo {

  List<@Nullable String> nbleStrings = List.of("a", null, "c");
  List<@NonNull String>  nnStrings = List.of("a", "b", "c");

  void client() {
    library(nbleStrings);
    library(nnStrings);
    library2(nbleStrings);
    library2(nnStrings);
  }

  void library(List<? extends @Nullable String> strings) {
    for (String s : strings) {
      if (s != null) {
        s.hashCode();
      }
    }
  }

  void library2(List<@PolyNull String> strings) {
    for (String s : strings) {
      if (s != null) {
        s.hashCode();
      }
    }
  }
}


--

---
You received this message because you are subscribed to the Google Groups "Checker Framework discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to checker-framework-...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/checker-framework-discuss/f412a394-e0f2-4cb3-b477-1aa40323b87fn%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages