Search code examples
kotlinnull-checkkotlin-null-safety

kotlin safe and non-null operation


if (intent.extras?.getBoolean(AppConstants.KEY_IS_FROM_NOTIFICATION) == true) {
    val intent = Intent(
        this, SplashScreen::class.java
    ).apply {
        addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    }
    startActivity(intent)
} else {
    finish()
}

What if intent.extras is null. If its null what will happen to the statement

if (intent.extras?.getBoolean(AppConstants.KEY_IS_FROM_NOTIFICATION) == true)


Solution

  • The ?. in Kotlin is a simple null check: Taking this into consideration, the output of the if (...) would simply be false, on intent.extras being null.

    For better understandability of the ?. operator, I've written the same if statement in java below:
    if (intent.extras != null && intent.extras.getBoolean(...) == true) {...}

    If you'd like to create custom logic right after the ?., you can do so, by using the elvis operator ?:. The elvis is nothing but a "ternary-null-check".