Martin
Martin

Reputation: 24308

Java: Ternary operator, not working as should

I have some sample code and it looks like it uses a ternery operator but it takes 3 items. So I am really confused, the ones I have seen in other languages take only 2, i.e. true and false.

Here is the code

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

what i wish to do is remove the line

     : analytics.newTracker(R.xml.ecommerce_tracker);

So it would now be

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

but it states it is missing a : (colon) in the IDE. So maybe this isn't a ternery operator after all ?

THe ide I am using is Android Studio.

I know it must be something simple, but i can't figure it out.

Any ideas ?

Upvotes: 2

Views: 427

Answers (2)

Rudi Kershaw
Rudi Kershaw

Reputation: 12972

What you have there is nested ternary operators. Think of them as the following (pseudo-code below)

  condition ? answerifTrue : secondternaryoperator;
  where secondternaryoperator =
        secondcondition ? answerifTrue : answerIfFalse;

Basically, this is two ternary operators combined. If the first condition is true it simply returns answerifTrue. But if the condition is false, it runs the second ternary operator to determine what to return based on a second condition. A singular ternary operator simply looks like this;

  condition ? answerifTrue : answerIfFalse;        

So if you want to create a single ternary operator from both you need to determine which answer you want if the first condition is false, for example;

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

I imagine however, that what you need isn't well suited to ternary operators anyway and you might need to restructure the statement entirely into if else blocks or a switch statement.

Upvotes: 3

Kody
Kody

Reputation: 1254

Hm, as far as I understand that use case you have to do something like this:

 Tracker t = null; 

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

Upvotes: 0

Related Questions