2

Given the code:

public Statement methodCallByName(MethodDeclaration method, String string) {
    List<ExpressionStatement> expressions = method.getBody().statements().stream()
                                                .filter(s -> s instanceof ExpressionStatement)
                                                .map(ExpressionStatement.class::cast)
                                                .collect(Collectors.toList());
    return null;
}

I have the following error in Eclipse Oxygen:

enter image description here

Notice that statements() returns a List according to JDT docs.

What is wrong?

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
AlexSC
  • 1,823
  • 3
  • 28
  • 54
  • did you try `javac`? – Eugene Oct 25 '18 at 14:27
  • 2
    That’s the standard [*raw types*](https://stackoverflow.com/q/2770321/2711488) problem. `statements()` returns the *raw type* `List`, hence, all the benefits of Generics are disabled beyond that point. – Holger Oct 25 '18 at 14:37

1 Answers1

8

The problem is caused by statements() returning the raw type List (see also What is a raw type and why shouldn't we use it?).

Raw types may not only provoke unchecked operations, but also limit the applicability of type inference.

You may fix it with

public Statement methodCallByName(MethodDeclaration method, String string) {
    List<?> statements = method.getBody().statements();
    List<ExpressionStatement> expressions = statements.stream()
        .filter(s -> s instanceof ExpressionStatement)
        .map(ExpressionStatement.class::cast)
        .collect(Collectors.toList());
    // ...
    return null;
}

The conversion from the raw type List to a list of unknown element type List<?>, is the only type safe conversion we can do here. Since you are going to check and cast the elements anyway, that’s no restriction.

But note that you should try to be consistent. Use either

.filter(s -> s instanceof ExpressionStatement)
.map(s -> (ExpressionStatement)s)

or

.filter(ExpressionStatement.class::isInstance)
.map(ExpressionStatement.class::cast)
Holger
  • 285,553
  • 42
  • 434
  • 765