eclipse-jdt / eclipse-jdt/eclipse.jdt.core

Incorrect unnecessary cast warning from ECJ

Open
#3,636 4 comments 0 reactions 1 assignee Claimed by @srikanth-sankaran View on GitHub
bug
Dominant language
Java
Stars
237
Forks
195
Avg merge
1d 12h
Merged PRs (30d)
47

Description

This issue comes from https://bugs.eclipse.org/bugs/show_bug.cgi?id=569616

The problem still exists in 2024-12.

When I call a generics method from within a stream I might need a cast. But Eclipse thinks it doesn't and so it suggests to remove the cast. Following this advice will lead to a compile error.

If I have the code
```
public class GenericsCast {

public static void main(String[] args) throws Exception {
Set input = Set.of("1", "2", "3");
Set result = createFoos(input);
System.out.println(result);
}

private static Set createFoos(Set input) {
return input.stream().map(s -> {
return (Foo) createFoo(s); // <== Warning
}).collect(Collectors.toSet());
}

static class Foo {

public final String s;

public Foo(String s) {
this.s = s;
}
}

static E createFoo(String s) {
@SuppressWarnings("unchecked")
E result = (E) new Foo(s);
return result;
}
}
```
then Eclipse will show me a warning "Unnecessary cast from GenericsCast.Foo to GenericsCast.Foo".

The quickfix will then change the method to
```
private static Set createFoos(Set input) {
return input.stream().map(s -> { // <== Error
return createFoo(s);
}).collect(Collectors.toSet());
}
```
which will show an error "Type mismatch: cannot convert from Set to Set".

I'm not entirely sure where the problem is, but note that
```
private static Set createFoos(Set input) {
return input.stream().map(s -> {
Foo foo = createFoo(s);
return foo;
}).collect(Collectors.toSet());
}
```
works fine.

The quickfix suggestion:

![image](https://github.com/user-attachments/assets/9388ae0e-175b-4560-b52f-1ba7c5d366fb)

After the quickfix:

![image](https://github.com/user-attachments/assets/d5f462f5-5fe6-4437-9877-ebe7be39c019)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.