If I have a nullable Boolean b
, I can do the following comparison in Java:
Boolean b = ...;
if (b != null && b) {
/* Do something */
In case if you want to perform operations alike
contain
on aString
you could use equality check like below -
if (url?.contains("xxx") == true){
return 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-> {}
}
In Kotlin, you can do like this:
val b: Boolean? = true
if (b == true) { // if b is null, this should be null == true
/* Do something */
} else {
/* Do something else */
}
You can do with safe Operator "let"
val b: Boolean? = null
b?.let { flag ->
if(flag){
// true Block
} else {
// false Block
}
}
Kotlin will statically analyze your null checks. This is fine:
val b: Boolean? = null
if (b != null && b) {
println(b)
}
Even though this fails with type error:
val b: Boolean? = null
if (b == null && b) {
println(b)
}
For more see: http://kotlinlang.org/docs/reference/null-safety.html
You can also use "null coalescing operator" (which will work for mutable variables):
val b: Boolean? = null
if (b ?: false) {
println(b)
}
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
}