karlsebal
karlsebal

Reputation: 1761

How to check a nullable boolean in kotlin

if I want to check a nullable Boolean I get a type mismatch

var bool: Boolean? = true

if(bool) 
  println("foo") 
else 
  println("bar")

because Boolean is expected not Boolean?

Upvotes: 4

Views: 5887

Answers (3)

Alexey Romanov
Alexey Romanov

Reputation: 170909

If you want to treat null case differently from either true or false:

when(bool) {
    null -> println("null")
    true -> println("foo")
    false -> println("bar")
}

Upvotes: 5

Dak28
Dak28

Reputation: 259

When you have nullable type my suggestion is this:

If you put nullable for a reason it means that variable could be nullable, so before do anything you have to check if it's not null.

 val bool: Boolean? = null

     if(bool != null) {
         if(bool){
             println("foo")
         } else {
             println("foo")
         }
    } else {
    println("variable non instancied yet")
   }

Upvotes: -1

karlsebal
karlsebal

Reputation: 1761

use Boolean.equals()

var bool: Boolean? = null

if(true.equals(bool)) 
  println("foo") 
else 
  println("bar")

it is even possible to do this inline

var bool: Boolean? = null

if(true == bool) 
  println("foo") 
else 
  println("bar")

Or use elvis nullable boolean check

var bool: Boolean? = null

if(bool ?: false) 
  println("foo") 
else 
  println("bar")

Upvotes: 3

Related Questions