Java ternary operator influence on generics type inference -
public list<string> foo1() { list<string> retval = bar(); if (retval == null) homecoming collections.emptylist(); else homecoming retval; } public list<string> foo2() { list<string> retval = bar(); homecoming retval == null ? collections.emptylist() : retval; }
why foo1() compiles fine whereas foo2() has error? (to more precise "type mismatch: cannot convert list<capture#1-of ? extends object> list<string>")
i have thought both functions compile same bytecode, clever compiler should infer right type emptylist()...
compiles me fine in java 8.
earlier versions of java might need more help
return retval == null ? collections.<string>emptylist() : retval; should work.
edit due improvements in java 8 type inference explained here
http://openjdk.java.net/jeps/101
and here's blog highlights: http://blog.jooq.org/2013/11/25/a-lesser-known-java-8-feature-generalized-target-type-inference/
java generics compiler-errors java-7
No comments:
Post a Comment