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

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)

Tags:

Java