Amit Yadav
Amit Yadav

Reputation: 35114

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)

Upvotes: 0

Views: 54

Answers (1)

Z-100
Z-100

Reputation: 591

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".

Upvotes: 1

Related Questions