Is there a way to do a java ternary operation without doing an assignment or way to fake the assignment?
OK, so when you write a statement like this:
(bool1 && bool2) ? voidFunc1() : voidFunc2();
there are two distinct problems with the code:
The 2nd and 3rd operands of a conditional expression1 cannot be calls to void methods. Reference: JLS 15.25.
An expression is not a statement, unless it is either and assignment expression OR a method call OR a object creation. Reference: JLS 14.8.
In fact, the second of these problems is a syntax error and I would expect any mainstream Java compilers to report it instead of the first problem. The first problem would only reveal itself if you did something like this:
SomeType dummy = (bool1 && bool2) ? voidFunc1() : voidFunc2();
or
gobble((bool1 && bool2) ? voidFunc1() : voidFunc2());
where gobble
is a method that does nothing ... except "consume" the value of its argument.
AFAIK, there is no context in which the original expression is acceptable.
However, there are ways to wrap the void
functions so that they can be called in a conditional expression. Here is one:
int dummy = (bool1 && bool2) ?
() -> {voidFunc1(); return 0;} :
() -> {voidFunc2(); return 0;};
1 - "Conditional expression" is the primary term used for this construct in the Java Language Specification. It is called the "ternary conditional operator" in Oracle Java Tutorial.