This doesn’t compile and gives the following error: Illegal start of expression. Why?
public static AppConfig getInstance() {
return mConfig != null ? mConfig : (throw new RuntimeException("error"));
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is because a ternary operator in java takes the form
expression ? expression : expression, and you are giving a statement as the final part. This doesn’t make sense as a statement doesn’t give a value, while expressions do. What is Java meant to do when it finds the condition to be false and tries to give the second value? There is no value.The ternary operator is designed to allow you to quickly make a choice between two variables without using a full
ifstatement – that isn’t what you are trying to do, so don’t use it, the best solution is simply:The ternary operator isn’t designed to produce side effects – while it can be made to produce them, people reading it won’t expect that, so it’s far better to use a real
ifstatement to make it clear.