0

I'm getting a compile error in Eclipse on line 11.

Type mismatch: cannot convert from List<Object> to List<JavaCompilerBug.Foo>

I believe this code should compile and I've created a short example that demonstrates the problem:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;

public class JavaCompilerBug {

  public static void main(String[] args) {
    List<String> vals = Arrays.asList("1", "2", "3");

    List<Foo> foos = map(vals, s -> Foo.with(last(vals)));
  }

  public static class Foo {
    public static Foo with(String value) {
      return new Foo();
    }

    public static Foo with(Foo value) {
      return new Foo();
    }
  }

  public static <A, B> List<B> map(List<A> input, Function<A, B> function) {
    List<B> ret = new ArrayList<>();
    for (A element : input) {
      ret.add(function.apply(element));
    }
    return ret;
  }

  public static <T> T last(List<T> c) {
    return c.get(c.size() - 1);
  }

}
satnam
  • 10,719
  • 5
  • 32
  • 42
  • 4
    It seems to be an inference bug (happens with eclipse). Using explicit type witnesses with either `map` or `last` solve the problem. Compiles fine with `javac` regardless. – Jorn Vernee Mar 24 '18 at 17:50
  • 5
    Compiles fine with javac from 9.0.4 and 10 both. – Naman Mar 24 '18 at 17:50
  • This must be a problem with eclipse then if it works with javac. – satnam Mar 24 '18 at 17:52
  • I keep running into type inference failures with Eclipse (almost to the point where a canonical would be justified). I'm too lazy too submit bug reports though, so feel free to self-answer the question with a link to the bug report you're making. – Jorn Vernee Mar 24 '18 at 18:05
  • 2
    When attempting to find bugs in the Java compiler, make sure that you actually use the Java compiler ;) – Jacob G. Mar 24 '18 at 21:45

1 Answers1

4

The problem is actually with Eclipse and not the Java compiler. This issue has been filed with Eclipse here: https://bugs.eclipse.org/bugs/show_bug.cgi?id=532860

satnam
  • 10,719
  • 5
  • 32
  • 42