Kotlin Condition is always true if val used

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"
                }
        }

>Solution :

Your if is already checking for the true value of isNumber, so 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 its false because my if block
is already checking if its true, let my if do the heavy lifting and leave my else to just wake up when isNumber becomes false, no need to remind my poor else, leave him be…

Leave a Reply