Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a nullable boolean in kotlin

Tags:

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?

like image 462
karlsebal Avatar asked Sep 17 '25 06:09

karlsebal


1 Answers

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

when(bool) {
    null -> println("null")
    true -> println("foo")
    false -> println("bar")
}
like image 198
Alexey Romanov Avatar answered Sep 19 '25 02:09

Alexey Romanov