Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty List in conditional expression in Java [duplicate]

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.

like image 449
Tiny Avatar asked Mar 05 '26 21:03

Tiny


1 Answers

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.

like image 147
Bhesh Gurung Avatar answered Mar 08 '26 09:03

Bhesh Gurung