Use of Boolean? in if expression

You can compare nullable boolean with true, false or null using equality operator:

var b: Boolean? = null
if (b == true) {
    // b was not null and equal true
} 
if (b == false) {
   // b is false 
}
if (b != true) { 
   // b is null or false 
}

If you want to cleanly check whether a Boolean? is true or false you can do:

when(b) {
    true -> {}
    false -> {}
}

If you want to check if it's null you can add that (or else) as a value in the when:

when(b) {
    true -> {}
    false -> {}
    null -> {}
}

when(b) {
    true -> {}
    false -> {}
    else-> {}
}

Tags:

Null

Kotlin