How to run code if an object is null?

In Kotlin, I can run the code if the object does not have a null value:

data?.let {
    ... // execute this block if not null
}

but how can I execute a block of code if the object is null?

+26
source share
6 answers

Just use regular if:

if (data == null) {
  // Do something
}
+12
source

You can use the elvis operator and evaluate another block of code with run { ... }:

data?.let {
    // execute this block if not null
} ?: run {
    // execute this block if null
}

But this does not seem to be as readable as a simple if- operator else.

Also, you can find this Q & useful:

+82
source

​​ , :

infix fun Any?.ifNull(block: () -> Unit) { 
  if (this == null) block()
}

:

data ifNull {
  // Do something
}
+23

. , , .

data ?: doSomething()
+10

myNullable?.let {

} ?: { 
    // do something
}()

fun()

myNullable?.let {

} ?: fun() { 
    // do something
}()

invoke() ()

myNullable?.let {

} ?: fun() { 
    // do something
}.invoke()

, , .

val res0 = myNullable?.let {
} ?: () {

}()
val res1 = myNullable?.let {
} ?: fun() {
    "result"    
}()
val res2 = myNullable?.let {
} ?: () {
    "result"    
}()


println("res0:$res0")
println("res1:$res1")
println("res2:$res2")

:

res0:kotlin.Unit // () {} with empty
res1:kotlin.Unit // fun() {}
res2:result      // () {} with return
+1

, when:

when(myVariable){   
    null -> {
            // execute your null case here
        }
    else -> { // non null case }
}

when , , .

0

Source: https://habr.com/ru/post/1684134/


All Articles