Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rewrite multiple ternary "? :" in terms of "if" statements?

Tags:

java

I understand that:

value = (a > b) ? a : b;

is the same as:

if (a > b)
  value = a;
else
  value = b;

But I'm having trouble deciphering what this means:

EDIT (the previous example I used was not good, this is real code from another example):

Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics.newTracker(PROPERTY_ID)
      : (trackerId == TrackerName.GLOBAL_TRACKER) ? analytics.newTracker(R.xml.global_tracker)
          : analytics.newTracker(R.xml.ecommerce_tracker);

How do I rewrite the last equation in terms of if, else if, and else?

like image 948
user2323030 Avatar asked Feb 12 '26 01:02

user2323030


2 Answers

You need a second conditional for this ternary expression to work.

value = (a > b) ? a : (b > c) ? c : d;

Then it would become:

if (a > b) {
    value = a;
} else if (b > c) {
    value = c;
} else {
    value = d;
}

In your case:

if (trackerId == TrackerName.APP_TRACKER) {
    t = analytics.newTracker(PROPERTY_ID);
} else if (trackerId == TrackerName.GLOBAL_TRACKER) {
    t = analytics.newTracker(R.xml.global_tracker);
} else {
    t = analytics.newTracker(R.xml.ecommerce_tracker);
}

Resources:

  • Multiple conditions in ternary operators
like image 172
martynas Avatar answered Feb 14 '26 14:02

martynas


So based on the example you linked:

Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics.newTracker(PROPERTY_ID)
      : (trackerId == TrackerName.GLOBAL_TRACKER) ? analytics.newTracker(R.xml.global_tracker)
          : analytics.newTracker(R.xml.ecommerce_tracker);

Which you seemed to have used to produce value = (a > b) ? a : b ? c : d;, which should probably be more like, value = (a == b) ? c : (a == d) ? e : f, it would read something like...

Tracker t = null;
if (trackerId == TrackerName.APP_TRACKER) {
    t = analytics.newTracker(PROPERTY_ID);
} else if ((trackerId == TrackerName.GLOBAL_TRACKER)) {
    t = analytics.newTracker(R.xml.global_tracker);
} else {
    t = analytics.newTracker(R.xml.ecommerce_tracker);
}
like image 20
MadProgrammer Avatar answered Feb 14 '26 16:02

MadProgrammer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!