amaembo / streamex

Enhancing Java Stream API
Apache License 2.0
2.18k stars 249 forks source link

Issue with java wildcard #236

Closed foal closed 3 years ago

foal commented 3 years ago

Have a simple code

    @SuppressWarnings("resource")
    private static <R> List<R> getMissingItems(List<? extends R> freshItems, List<? extends R> oldItems, 
                                                                           Function<? super R, String> idFunc) {
        List<String> idList = StreamEx.of(freshItems).map(idFunc::apply).toList();
        //Java stream works
        List<R> result = oldItems.stream()
            .filter(e -> !idList.contains(idFunc.apply(e)))
            .collect(Collectors.toList());
        //StreamEx - Type mismatch: cannot convert from List<capture#19-of ? extends R> to List<R>
        result = StreamEx.of(oldItems)
            .remove(e -> idList.contains(idFunc.apply(e)))
            .toList();
        return result;
    }

So part with StreamEx can't be compiled due to the error: Type mismatch: cannot convert from List<capture#19-of ? extends R> to List<R>

amaembo commented 3 years ago

Yes, it's an unfortunate consequence of Java type system and there's nothing that could be fixed on the library side. You can avoid this problem adding a bogus .<R>map(x -> x) step or just using traditional .collect(Collectors.toList());. Note that it's planned to add to Java 16 a new toList() method right into the java.util.Stream, and it will suffer the same problem.