Anton Balaniuc
Anton Balaniuc

Reputation: 11739

Raw type predicate causes compilation error

I don't understand why raw type Predicate causes compilation error even if I have a type cast. Let's look at the following example:

From a list containing different objects get the ones which extend Number, cast to a Number and collect to a List.

List<Object> objectList = Arrays.asList(1, 3.4, 2, new Object(), "");

List<Number> numbers = objectList
        .stream()
        .filter(Number.class::isInstance)
        .map(Number.class::cast)
        .collect(Collectors.toList()); 

Let's do the same thing, but this time let's cast Number.class::isInstance to Predicate:

List<Number> numbers1 = objectList.stream()
                .filter((Predicate) Number.class::isInstance)
                .map(Number.class::cast)
                .collect(Collectors.toList());

This leads to a compilation error:

Error:(28, 25) java: incompatible types: java.lang.Object cannot be converted to java.util.List

There is a cast after a filter operation .map(Number.class::cast) and .collect(Collectors.toList());But the final type is java.lang.Object. Why do you think the result type is java.lang.Object and not a List<Number>?

Upvotes: 4

Views: 262

Answers (1)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272517

  1. As you've supplied a raw type to filter, it returns a raw Stream.
  2. Ordinarily, map would be <R> Stream<R> Stream<T>::map(Function<? super T, ? super R> function). But now there is no T, so the argument is forced to be a raw Function type, so map too ends up returning a raw Stream.
  3. Similar logic means that collect returns an Object.

Upvotes: 3

Related Questions