12
votes

The following code works fine in all online java compilers but eclipse throws compiler error. Is it a bug in eclipse or am I missing some setting somewhere? A simple fix to silence eclipse? online: https://ideone.com/l0bbhz. Note: This is a simplified cooked-up example to just point to the problem. I understand flatMap is not necessary in this case. In the actual case, I really need flatMap

package dummy;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static java.util.stream.Collectors.toList;

public class LearnJava {

    public static void main(String[] args) {
        String[] sa = {"ne", "two", "three"};
        List<String> l = Arrays.stream(sa)
                .flatMap(s -> Collections.singleton(s).stream().map(c -> c.toUpperCase()))
                .collect(toList());
        System.out.println(l.get(0));
    }

}

Error in eclipse console.

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    Type mismatch: cannot convert from List<Object> to List<String>

    at dummy.LearnJava.main(LearnJava.java:13)

My eclipse version:

Eclipse Java EE IDE for Web Developers.

Version: Luna Service Release 2 (4.4.2) Build id: 20150219-0600


Update: I went with this minor workaround. It works without major refactoring!

.flatMap(s -> Collections.singleton(s).stream().map(c -> c.toUpperCase()))

To

.<String>flatMap(s -> Collections.singleton(s).stream().map(c -> c.toUpperCase()))
1
I can confirm this behaviour. I am using Eclipse Mars.2 and JDK 1.8.0_92. - Turing85
@SeekAddo this is not a problem of the JDK. My JDK is up-to-date and the program compiles fine on console. This is a problem with Eclipse. - Turing85
@balki jsyk you should replace flatMap and Collections.singleton(s).stream().map(c -> c.toUpperCase()) with map and s.toUpperCase()--this shouldn't make a difference re: type inference on toList - obataku
as @oldrinb mentioned: the troubling part for Eclipse is the call to flatMap(...). Writing [...].<String>flatMap(...) instead of [...].flatMap(...) makes Eclipse resolve the rest of the types just fine. - Turing85
Eclipse was quite late to adopt to streams and lambdas and is sometimes still struggeling today. Don't try this with old Luna. In my installation ( Mars.2 Release (4.5.2) Build id: 20160218-0600) your code works fine. - mtj

1 Answers

2
votes

The Eclipse compiler is not perfect. Sometimes you'll hit issues such as this. For example, there are currently two bugs open related to flatMap and type interference - 482664 and 502158.

If you believe the code is legit, which is strongly the case when javac compiles it without issues, then you should open a bug and post a snippet there in order to let them know about it. This helps improving the compiler.