Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple parameters with ternary operator

method(b ? "hello" : "hi", "whats", "going", "on");

When b == true what I get is is: "hello", "whats", "going", "on";

However what I actually want is:

method(b ? "hello" : ((((("hi", "whats", "going", "on"))))));

Thank you in advance.

like image 203
Bob Avatar asked Jan 28 '26 18:01

Bob


2 Answers

The trenary operator must return the same type for both clauses (in your case, the "true" clause is a String, and it's unclear what is the "false" clause - but you probably want String[]).

You can partially solve it by always returning a String[]:

method(b?new String[] {"hello"}:new String[] {"hi", "whats", "going", "on"});
like image 162
amit Avatar answered Jan 31 '26 06:01

amit


The first thing I did was to blindly give it a shot in Eclipse, but obviously I could not get anything close to what you're asking for, so instead of just going with try/fail, I took a look at the Java BNF grammar to see what is the shortest syntactically correct way to declare a collection without assignment to a variable.

Assuming that you are trying to avoid declaring extra variables but want the parameters created straight away, I would use the following, which in my humble opinion is the shortest and closest syntactically correct way to get what you want :

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {

         boolean b = false;

         methodSample(b ? new String[]{"Hello"} : new String[]{"hi", "whats", "going", "on"});

    }

    public static void methodSample(String[] args)
    {
        System.out.println(Arrays.toString(args));
    }

}

However, a cleaner way to do it would probably be :

public static void main(String[] args) {

    boolean b = false;

    String[] val1 = {"hello"};
    String[] val2 = {"hi", "whats", "going", "on"};

    methodSample(b ? val1 : val2);

}
like image 29
user3856210 Avatar answered Jan 31 '26 08:01

user3856210