abbath0767
abbath0767

Reputation: 986

How to properly handle a null variable perspective in kotlin?

My old java version method looks like:

@Override
public void closeSimpleAlertDialog() {
    if (mAlertDialog != null && mAlertDialog.isShowing()) {
        mAlertDialog.dismiss();
    }
}

As you can tell it is checked whether the null reference link to a dialog mAlertDialog and if not null check call method isShowing(), and only then caused a method of close - dismiss(). Very simple

I faced a problem - how is still in "Kotlin-style" to perform the same operation?

My first version looks here:

if (mAlertDialog != null && mAlertDialog?.isShowing) {
        mAlertDialog?.dismiss()
}

Next step change mAlertDialog != null && mAlertDialog?.isShowing to mAlertDialog?.isShowing ?: false and last version looks like:

if (mAlertDialog?.isShowing ?: false)
            mAlertDialog?.dismiss()

But I don't understand. Why do I need "?" if the null checking already happened before (here: mAlertDialog?.)?

Upvotes: 1

Views: 387

Answers (3)

Mattia C.
Mattia C.

Reputation: 731

mAlertDialog?.isShowing ?: false

This line is providing a fallback value (false) in case the dialog or the property is null.

What you are probably looking for is:

alertDialog?.let {
    if (it.isShowing())
        it.dismiss()
}

Where "it" is the property before the question mark null-checked. If alertDialog is null, the let will not be called and note that if you call it without the question mark it will enter even if it's null.

Upvotes: 4

Avijit Karmakar
Avijit Karmakar

Reputation: 9388

If you use ? then you are allowing the null value for the variables.

Example:

var a: String = "abc"
a = null // compilation error

var b: String? = "abc"
b = null // ok

b?.length

This returns b.length if b is not null, and null otherwise.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691715

Because another thread might make the property null after the null check, and before the call to dismiss. It won't happen if you use a local variable, or let.

BTW, if you omit the question mark and hover on the red squiggly, IntelliJ tells you

Smart cast to Dialog is impossible, because mAlertDialog is a mutable property that could have been changed by this time

The canonical way (AFAIK) to do that with Kotlin would be

fun close() {
    mAlertDialog?.let { 
        if (it.isShowing) {
            it.dismiss()
        }
    }
}

Upvotes: 4

Related Questions