如何修复‘opperator && 无法应用于boolean’错误?尝试(requestCode)&&(requestCode=Result)无效
Hey there, let's break down what's going on here and fix that error.
First, let's clarify why you're seeing this message: Most strongly-typed languages (like Java, C#, etc.) don't let you use non-boolean values directly with the && logical operator. The && requires both sides of the operator to evaluate to a boolean (true/false), but your original code (and your attempted fix) is using a value like an integer (requestCode) directly, which isn't a boolean.
Your attempted fix (requestCode)&&(requestCode=Result) doesn't work for two key reasons:
- The left side
requestCodeis still a non-boolean value (like an int), so the language can't interpret it as a boolean for the&&check. - The right side
requestCode=Resultis an assignment, not a boolean check. This returns the value being assigned (the value ofResult), which is also non-boolean—so even if the left side worked, the right side would still trigger the same error.
Here's how to fix it, depending on your goal:
Scenario 1: You want to check if requestCode is valid (e.g., non-zero) AND equals Result
If your aim is to run code only when requestCode meets both conditions, rewrite the expression to use explicit boolean checks on both sides:
// Example for int-type requestCode if (requestCode != 0 && requestCode == Result) { // Your code here }
requestCode != 0converts the numeric value to a boolean (trueif non-zero,falseotherwise)requestCode == Resultchecks if the values match, also returning a boolean- Now
&&has two valid boolean operands, which is exactly what the language expects.
Scenario 2: You want to assign Result to requestCode only if requestCode is valid
If you're trying to conditionally assign the value (not just check it), you can't use && here. Instead, use an if statement:
if (requestCode != 0) { // Adjust the condition to match your "valid" definition requestCode = Result; }
Or if you prefer a shorter one-liner, use the ternary operator:
requestCode = (requestCode != 0) ? Result : requestCode;
Quick recap
Always make sure both sides of && evaluate to a boolean. Never use raw numeric/non-boolean values directly with logical operators in strongly-typed languages—explicitly write the boolean check (like != 0, == someValue, etc.).
内容的提问来源于stack exchange,提问作者Kadi Simpson

