checker-framework icon indicating copy to clipboard operation
checker-framework copied to clipboard

filter(Objects::nonNull) seems not work

Open blackdiz opened this issue 3 years ago • 3 comments

Hi, when I try filter(Objects::nonNull) to filter out any null value and then use map to apply a lambda, the checker framework seems to complain about the incompatible receiver type, here's a simple test example:

        @Test
	void test() {
		List<@Nullable String> s = new ArrayList<>();
		s.add("abc");
		s.add(null);
		s.add("cdf");
		System.out.println(s.stream().filter(Objects::nonNull).map(String::length).toList());
	}

And I got the following error:

error: [methodref.receiver] Incompatible receiver type
		System.out.println(s.stream().filter(Objects::nonNull).map(String::length).toList());
		                                                           ^
  found   : @Initialized @NonNull String
  required: @Initialized @Nullable String
  Consequence: method in @Initialized @NonNull String
    @Initialized @NonNull int length(@Initialized @NonNull String this)
  is not a valid method reference for method in @Initialized @NonNull Function<@Initialized @Nullable String, @Initialized @NonNull Integer>
    @Initialized @NonNull Integer apply(@Initialized @NonNull Function<@Initialized @Nullable String, @Initialized @NonNull Integer> this, @Initialized @Nullable String p0)

Is this a correct behavior? How can I make the code work?

blackdiz avatar Aug 03 '22 08:08 blackdiz

Thank you for the bug report. This is possibly related to #979. @smillst will look into it, probably in early September.

mernst avatar Aug 05 '22 14:08 mernst

Thank you, I find if I use collect(toList()) after filter, everything works fine:

     @Test
      void test() {
          List<@Nullable String> s = new ArrayList<>();
          s.add("abc");
          s.add(null);
          s.add("cdf");
          System.out.println(
              s.stream().filter(Objects::nonNull).collect(Collectors.toList()).stream()
                  .map(String::length)
                  .toList());
    }

blackdiz avatar Aug 06 '22 08:08 blackdiz

Thanks for the additional information; that is useful.

mernst avatar Aug 06 '22 17:08 mernst

This is a duplicate of https://github.com/typetools/checker-framework/issues/1345.

smillst avatar May 21 '24 18:05 smillst