vendredi 5 mai 2017

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

Aucun commentaire:

Enregistrer un commentaire