dvas0004 / NerdNotes

A collection of notes: things I'd like to remember while reading technical articles, technical questions I couldn't answer, and so on.
11 stars 0 forks source link

Kotlin: Top two null-safety tricks #118

Open dvas0004 opened 4 years ago

dvas0004 commented 4 years ago
fun main() {
    // the elvis operator
    val test = null    
    val test2 = test ?: "it was null"  
    println(test2)

    // taking action only if variable is non-null
    // using ?.let
    val isNull = null
    isNull?.let{
        println("Inside let with null - will not be printed")
    }

    val isNotNull = 1
    isNotNull?.let{
        println("Inside let with non-null value of '$it' - will be printed")
    }

}

Output:

it was null
Inside let with non-null value of '1' - will be printed
dvas0004 commented 4 years ago

https://kotlinlang.org/docs/reference/null-safety.html