2

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

5
  • 1
    You cannot use voids as part of ternar operator. Only two identical types. Commented May 5, 2017 at 7:44
  • Ternary operators don't work with void methods Commented May 5, 2017 at 7:44
  • 1
    "It is a compile-time error for either the second or the third operand expression to be an invocation of a void method." docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25 Commented May 5, 2017 at 7:45
  • 2
    using nested ternary operation is not a good practice .. Commented May 5, 2017 at 7:45
  • You could put your classes into a hierarchy where each implements an interface with the desired action in each class is an override. That's object-oriented programming and avoids the whole trouble and fragility and bug-prone behavior of casual reflection. You really don't want to use reflection much at all. For what you show here, odds are really good that standard programming techniques will serve you much, much better. Commented May 5, 2017 at 8:59

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks that's what I was missing.
Good Side Note.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.