I have this code in my app, but I don't understand how it is evaluated:
return chatBubble.myMessage() ? 1 : 0;
,
Could someone tell me how is this?
public int getItemViewType(int position) {
ChatBubble chatBubble = messages.get(position);
return chatBubble.myMessage() ? 1 : 0;
}
This is called in Java ternary operator , represented by the symbol
?
.According to the Java documentation :
It works like this in this case:
chatBubble.myMessage()
is true, it returns1
chatBubble.myMessage()
is false, return0
The ternary operator then has three parts:
Expressions for this operator are written like this:
To the left of
?
is the expression or value to be evaluated ( Expr ), to the left of:
is the resulting value if the evaluation of Expr is true, to the right of:
is the resulting value if the evaluation of Expr to be false.And since you use it with
return
, it will return the result1
or0
that it has exited the evaluation.NOTE:
This is the simplest form of ternary operator. There are more complex evaluations, nested operators etc. The truth is that they greatly simplify the code.
On that one line, you evaluate something that would otherwise have to be written like this:
We are talking about changing 5 lines of code for a single one, thanks to the ternary operator.