If I have a nullable Boolean b
, I can do the following comparison in Java:
Boolean b = ...;
if (b != null && b) {
/* Do something */
From what I've seen the Boolean? is a result of a method that returns Boolean on an object that is nullable
val person: Person? = null
....
if(person?.isHome()) { //This won't compile because the result is Boolean?
//Do something
}
The solution I've been using is to use the let
function to remove the possible returned null value like so
person?.let {
if(it.isHome()) {
//Do something
}
}
For Kotlin what i normally use is
if (object?.booleanProperty ==true)
{
//do stuff
}
this would only work when the property is true and the object is not null. For the reverse:
if (!object?booleanProperty !=true)
{
//do Stuff
}
Let's use an if-else
statement with an Elvis Operator
:
val a: Boolean?
val b: Boolean?
a = true
b = null
if (a != null ?: b) {
println("One of them isn't nullable...")
} else {
println("Both are nullables!")
}
// Result: "One of them isn't nullable..."
a = null
b = null
if (a != null ?: b) {
println("One of them isn't nullable...")
} else {
println("Both are nullables!")
}
// Result: "Both are nullables!"
It's pretty easy to add an extension function if that helps you.
fun Boolean?.orDefault(default: Boolean = false): Boolean {
if (this == null)
return default
return this
}
var x: Boolean? = null
if(x.orDefault()) {
..
}
first, add the custom inline function below:
inline fun Boolean?.ifTrue(block: Boolean.() -> Unit): Boolean? {
if (this == true) {
block()
}
return this
}
inline fun Boolean?.ifFalse(block: Boolean?.() -> Unit): Boolean? {
if (null == this || !this) {
block()
}
return this
}
then you can write code like this:
val b: Boolean? = ...
b.ifTrue {
/* Do something in true case */
}
//or
b.ifFalse {
/* Do something else in false case */
}