The ternary (conditional) operator returns a value. If your methods don't, they can't be used as parts of the operator (where it takes the value).
In order to understand it better, let's think of one simple binary operator: +
. It works this way:
<eval1> + <eval2> --> <value>
It needs of 2 evaluable parts, and returns another.
If you typed
doThis() + doThat();
or even
gimmeAValue = doThis() + doThat();
it would fail, as neither doThis()
nor doThat()
evaluate to anything (they "return" void
).
Of course, both <eval1>
and <eval2>
must be of some "compatible" type in order the +
operator can handle them and return a value of some type.
Now let's see the ternary operator:
<evalBoolean> ? <eval1> : <eval2> --> <value>
It takes 3 evaluable parts, and returns a value.
The first evaluable part must be understandable (castable) by the compiler as a boolean. It will be used to decide which of the other 2 evaluable parts has to be returned.
The other two evaluable parts must be, well... evaluable. To something. Of some type.
In other words: the ternary conditional operator is intended to return something, not as code branching. Used this way:
gimmeAValue = testMe() ? returnThis() : returnThat();