If I used a variable
to check for boolean, the "!isNumber" is highlighted with the warning "Condition '!isNumber' is always true":
val isNumber = bind.number.isChecked
when (array) {
"A" -> {
if (isNumber) {
return "number"
} else if (!isNumber) {
return "letter"
}
}
However if I used the view directly to check for boolean, there is no warning:
when (acArray) {
"A" -> {
if (bind.number.isChecked) {
return "number"
} else if (!bind.number.isChecked) {
return "letter"
}
}
Your if
is already checking for the true
value of isNumber
, you don't need to explicitly check isNumber
in else
block if its false
, because the opposite of true
is false
that's why you get that warning.
Imagine the compiler talking to you:
Compiler:
Don't tell my
else
to check if itsfalse
because myif
block is already checking if itstrue
, let myif
do the heavy lifting and leave myelse
to just wake up whenisNumber
becomesfalse
, no need to remind my poorelse
, leave him be...
Edit: Sample scenarios below, class vs local vs top level file scope
Both classLevelScope
and localLevelScope
will give you a warning.
class MyClass {
val classLevelScope = false
fun function() {
if (classLevelScope) {
} else if (!classLevelScope) { // you'll get a warning here
}
}
}
class MyClass {
fun function() {
val localScope = false
if (localScope) {
} else if (!localScope) { // you'll get a warning here
}
}
}
But a Top level file scope will not
var isChecked = false // top level file scope, inside MyClass.kt
class MyClass {
fun function() {
if (isChecked) {
} else if (!isChecked) { // No warning here
}
}
}
My assumption for the top level scoped variable is that the compiler cannot determine who would change its value in what thread, class, instance of a class or from any other place because a top level scoped variable can be accessed anywhere unlike the classLevelScope
or the localLevelScope
which are only accessible outside using their enclosing scope. Your bind.number.isChecked
might be a top level scoped variable.
If the warning bothers you, you can remove it from your A.S settings
Inspections -> Kotlin -> Probable bugs -> Constant Condition -> Uncheck the box