Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA calling a method using a ternary operator [duplicate]

Tags:

java

ternary

I am trying to use ? to decide which method i want to call, but i do not need to assign a variable. My question: Is there a way to use the ternary operator with out assigning a variable?

(something i dont need) = (x == 1)? doThisMethod():doThatMethod()

instead of

if(x == 1) {
    doThisMethod()
} else {
    doThatMethod()
}
like image 902
Trae Moore Avatar asked Sep 28 '12 16:09

Trae Moore


People also ask

Can you call a function in a ternary operator?

Nope, you can only assign values when doing ternary operations, not execute functions.

Can ternary operator have multiple conditions?

We can nest ternary operators to test multiple conditions.

Can you chain ternary operators?

A Ternary Operator in Javascript is a special operator which accepts three operands. It is also known as the "conditional" or "inline-if" operator. Ternary Operator in Javascript makes our code clean and simpler. It can be chained like an if-else if....else if-else block.


2 Answers

This will not work, as it is not the intended use of the ternary operator.

If you really want it to be 1 line, you can write:

if (x==1) doThisMethod(); else doThatMethod();
like image 183
Kevin DiTraglia Avatar answered Sep 21 '22 12:09

Kevin DiTraglia


I doubt that this works. The JLS §15.25 defines the ternary expression as follows:

ConditionalExpression:
    ConditionalOrExpression
    ConditionalOrExpression ? Expression : ConditionalExpression

And a ConditionalExpression isn't a Statement by itself. It can be used in various other places, though, e.g. an Assignment:

AssignmentExpression:
    ConditionalExpression
    Assignment

Assignment:
    LeftHandSide AssignmentOperator AssignmentExpression
like image 44
Lukas Eder Avatar answered Sep 18 '22 12:09

Lukas Eder