Вопрос

In Java is it possible to use ternary to pass multiple arguments into a method call?

For example - in a method have:

    print(degree == 270 ? "e", 5 : "t", 6);

which calls:

    public void print(String s, int t){

    }

By using the ternary I want to pass in e and 5 OR t and 6. Without the need of having to duplicate code - like:

    print(degree == 270 ? "e" : "t", degree == 270? 5 : 6);

I don't think some understand, I don't want to use this method above, it runs the check an unnecessary time.

Это было полезно?

Решение

Why not

    (degree == 270) ? print("e", 5) : print("t", 6);

EDIT: apparently does not work in java :/

Другие советы

It would be possible if your expression consists of a wrapper object that has both of the values (s and t) as variables, but then you would have to instantiate both. For making your code better, I would try something like:

if(degree == 270) {
    print("e", 5);
}
else {
    print("f", 6);
}

or

switch(degree) {
    case 270:
        print("e", 5);
        break;
    default:
        print("f", 6);
        break;
}

as long as you compare to absoute values (not ranges).

I know it's not what you're looking for, but normally, in enterprise environments, this is the notation that would be recommended as it's the easiest to understand for others that will mantain the code and reduces risk of errors if some novice programmer has to change something.

At the end, the compiled code will be efficient either way. In fact, I'm thinking that your second option will go through the conditional expression twice, in which case it would be better just to use one of the alternatives I wrote.

Regards

A conditional expression (that's the official name) is an expression just like any other Java expression. As far as the surrounding method call is concerned, only its result matters. So clearly, you cannot use one expression to specify two arguments because each argument is its own expression.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top