Hi below statement throws error . It says "Not a statement"
map.containsKey(1)? someObject.setFlag(true) : map.put(1,"hello");
Is it needed to store the returned value in some variable on the left hand side of the statement?
Hi below statement throws error . It says "Not a statement"
map.containsKey(1)? someObject.setFlag(true) : map.put(1,"hello");
Is it needed to store the returned value in some variable on the left hand side of the statement?
You are using the Ternary
operator as a statement
, not an assignment
. In your case, you should use if else
if(map.containsKey(1)) {
someObject.setFlag(true)
}else{
map.put(1,"hello");
}
Here is the java docs of Ternary operator.
The ternary operator is an expression, not a statement. It is commonly used to set the value of a variable depending on some condition. In this case, you need to assign the result to a variable in order to make it into a statement:
String result = map.containsKey(1) ? someObject.setFlag(true) : map.put(1,"hello");
(Note: You should choose a better variable name.)
I think you will still have problems here because setFlag()
probably doesn't return a String
. Also, since you are creating side effects, you should replace this with an if
statement.