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;
For example, you should not try to make ternary operators nested inside of ternary operators. Although writing code this way works correctly in JavaScript, it is very hard to read and understand.
Remarks. The conditional operator (? :) is a ternary operator (it takes three operands). The conditional operator works as follows: The first operand is implicitly converted to bool .
The ternary operator is an operator that exists in some programming languages, which takes three operands rather than the typical one or two that most operators use. It provides a way to shorten a simple if else block. For example, consider the below JavaScript code. var num = 4, msg = ""; if (num === 4) {
Ternary operators can be nested just like if-else statements. Consider the following code: int a = 1, b = 2, ans; if (a == 1) { if (b == 2) { ans = 3; } else { ans = 5; } } else { ans = 0; } printf ("%d\n", ans); Here's the code above rewritten using a nested ternary operator: int a = 1, b = 2, ans; ans = (a == 1 ? (
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With