Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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…

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading