checker-framework
checker-framework copied to clipboard
filter(Objects::nonNull) seems not work
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?
Thank you for the bug report. This is possibly related to #979. @smillst will look into it, probably in early September.
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());
}
Thanks for the additional information; that is useful.
This is a duplicate of https://github.com/typetools/checker-framework/issues/1345.