What does a "+=" operator inside a ternary operator means?

Viewed 170

I came across a code snippet inside the androidx.lifecycle package and I was wondering what does this means.

LiveData.this.mActiveCount += mActive ? 1 : -1;

Where mActiveCount is an int, and mActive is a boolean.

But, as I was writting this question, I think I came with the answer, so if I'm not mistaken the "+=" operator, is used as we normally use the "=" operator.

This means that the order in which the code executes is the following:

the mActive ? 1 : -1; portion executes first.

Once this is resolved, the LiveData.this.mActiveCount += mActive executes. So my real question is:

Is this the correct equivalence of this code?:

    int intToAdd = mActive ? 1 : -1;
    activeCount += intToAdd;
4 Answers

The operator += is not concerned with ternary operator. You are checking for a condition using ternary operator and incrementing or decrementing it variable by 1.

a = a + b is equivalent to a += b, assuming we have declared a and b previously.

So, your code LiveData.this.mActiveCount += mActive ? 1 : -1; is equivalent to :-

 if(mActive){
    LiveData.this.mActiveCount += 1;
 }
 else{
   LiveData.this.mActiveCount -= 1;
 }

Your Logic below is also correct:-

 int intToAdd = mActive ? 1 : -1;
 activeCount += intToAdd;

This line of code adds either 1 or -1 to mAtiveCount, and looks at the boolean mActive to determine whether it adds +1 or -1.

It is exactly equivalent to this chunk of code, where I removed the usage of the tertiary operator and the += operator (and made their function explicit):

int amountToAdd;
if (mActive) {
  amountToAdd = 1;
} else { 
  amountToAdd = -1;
}
LiveData.this.mActiveCount = LiveData.this.mActiveCount + amountToAdd;

I think the line is a bit unclear, but could be made more clear with the judicious use of parenthesis:

LiveData.this.mActiveCount += (mActive ? 1 : -1);

Yes, you are right. There is something called as shorthand in java .

For example :

sum = sum + 1 can be written as sum += 1.

This statement :

LiveData.this.mActiveCount += mActive ? 1 : -1;

This statement really mean to say :

Either do this LiveData.this.mActiveCount += 1 or LiveData.this.mActiveCount += -1 based on mActive's value (true or false)

This can be answered by looking up Java operator precedence.

Assignment operators have the absolute lowest precedence, everything else happens first. The conditional expression mActive ? 1 : -1 is evaluated first. then the += is evaluated using the result of the condition expression.

Related