Pushparaj
Pushparaj

Reputation: 1049

conditional Operator ? : type evaluation

void method(Set<String> whiteListProviders){

        HashSet<String> hashedWhitelistedProviders;

        HashSet<String> fdsfh = (hashedWhitelistedProviders = (HashSet<String>) whitelistedProviders);

        HashSet<String> ghjk = (hashedWhitelistedProviders = new HashSet<String>(whitelistedProviders));

        HashSet<String> gh4jk = true ? fdsfh : ghjk; //compiles

        true?fdsfh:ghjk; //gives error "Type mismatch: cannot convert from HashSet<String> to boolean" 




}

I read http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25 but still couldn't understand why it is giving compilation error in eclipse

Upvotes: 1

Views: 86

Answers (1)

Mike Samuel
Mike Samuel

Reputation: 120506

Java only allows assignments and calls where a statement is expected, not arbitrary expressions.

From section 14.8 of the JLS:

Certain kinds of expressions may be used as statements by following them with semicolons:

ExpressionStatement:
        StatementExpression ;

StatementExpression:
        Assignment
        PreIncrementExpression
        PreDecrementExpression
        PostIncrementExpression
        PostDecrementExpression
        MethodInvocation
        ClassInstanceCreationExpression

The ternary operator (ConditionalExpression) is not on that list, so it can't appear except as part of a larger expression or initializer.

Upvotes: 5

Related Questions