The following segment of code issues a compiler error.
public List<Long> test()
{
boolean b=true;
return b ? Collections.emptyList() : Collections.emptyList();
}
incompatible types required:
List<Long>found:List<Object>
It requires a generic type like,
public List<Long> test()
{
boolean b=true;
return b ? Collections.<Long>emptyList() : Collections.<Long>emptyList();
}
If this ternary operator is removed such as,
public List<Long> test()
{
return Collections.emptyList();
}
or if it is represented by an if-else construct like,
public List<Long> test()
{
boolean b=true;
if(b)
{
return Collections.emptyList();
}
else
{
return Collections.emptyList();
}
}
then it compiles fine.
Why doesn't the first case compile? Tested on jdk-7u11.
In the case of ternary expression, compiler is not having the chance to infer the return type of the method Collections.emptyList() based on the return type of the test method. Instead, first it's having to resolve what the resulting type of the (ternary) expression would be. And since the type is not mentioned it becomes List<Object> and is incompatible with the return type of test method.
But in return Collections.emptyList(), it has the (right) context available (i.e. the return type of the test method) which it uses to infer what the return type of Collections.emptyList() should be.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With