sentientmachine
sentientmachine

Reputation: 357

Converting if/else-if/else to ternary operator in Java

I'm trying to convert an if-else statement to an equal statement using the ternary operator ?-:

My goal is to convert this code:

if (s instanceof Class1) {
    do_something((Class1) s);
} else if (s instanceof Class2) {
    do_something_else((Class2) s);
} else {
    do_that((Class3) s);
}

I worked out something like this:

(s instanceof Class1) ? do_something((Class1) s):
                     ((s instanceof Class2) ? (do_something_else(Class2) s))) :
                     (do_that((Class3) s));

The three methods I call just return void.

I get some syntax error when I write it. Can someone help or explain what am I missing? Thanks in advance

Upvotes: 2

Views: 4178

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074385

There are two reasons you can't do that:

  1. You can't use just any freestanding expression as a statement. Unlike some languages (JavaScript, for instance), Java doesn't have the general concept of an "expression statement," there are only some expressions that are also allowed as statements (like method calls).

  2. The conditional operator must have a result, but if your methods are void, they don't produce one.

Just keep the if/else.


Side note: A series of if/else with instanceof tends to suggest a design issue that it may be possible to address in a cleaner way.

Upvotes: 3

Related Questions