Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

generics - Java if ternary operator and Collections.emptyList()

Could you please explain why with the first return type the code can't be compiled? The message is : Type mismatch: cannot convert from List<capture#1-of ? extends Object> to List<String>.

Is there inserted an explicit cast in the second case ?

public class GenericsTest {

        private String getString() {
            return null;
        }

        public List<String> method() {
            String someVariable = getString();
            //first return type
            //return someVariable == null ? Collections.emptyList() : Collections.singletonList(someVariable);
            //second return type
            if (someVariable == null) {
                return Collections.emptyList();
            } else {
                return Collections.singletonList(someVariable);
            }
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Because of type inference rules. I don't know why exactly (you should check the JSL, the ternary operator section), but it appears the ternary expression does not infer the type parameter from the return type.

In other words, the type of the ternary expression depends on the types of its operands. But one of the operands has undetermined type parameter (Collections.emptyList()). At that point the ternary expression still does not have a type, so it cannot influence the type parameter. There are two types to be inferred - one is the result of the ternary expression, and the other is the type parameter of the .emptyList() method.

Use Collections.<String>emptyList() to explicitly set the type


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...