简体   繁体   中英

Null check in if conditions

I have this code in Java

return mFingerprintManager.hasEnrolledFingerprints() &&
       createKey(DEFAULT_KEY_NAME, true) &&
       initCipher(mCipher, DEFAULT_KEY_NAME);

which I have converted to Kotlin as shown here

return mFingerprintManager.hasEnrolledFingerprints() &&
        createKey(DEFAULT_KEY_NAME, true) &&
        if (mCipher != null) {
            mCipher?.apply { initCipher(this, DEFAULT_KEY_NAME) }
            return true
        } else {
            return false
        }

Is there a better way to write the Kotlin code so it is more concise? Variable mCipher is defined as

private var mCipher: Cipher? = null

at the class level.

?. on a nullable receiver returns the result of the function if the receiver is not null, and null otherwise.

Combining this with .apply we can write:

[..] && mCipher?.apply { initCipher(this, DEFAULT_KEY_NAME) } != null

Wait, why can't you copy-paste the Java code to Kotlin? It will work as-is:

return mFingerprintManager.hasEnrolledFingerprints()
       && createKey(DEFAULT_KEY_NAME, true)
       && initCipher(mCipher, DEFAULT_KEY_NAME)

If initCipher(...) can handle null as its parameter, then you don't need to check mCipher before passing it to the method.

Update:

It seems that you've converted initCipher from Java to Kotlin, and now it can't accept null as its argument. Then, assuming you don't have a concurrent access to mCipher , add a null-assertion !! to the code:

return mFingerprintManager.hasEnrolledFingerprints()
       && createKey(DEFAULT_KEY_NAME, true)
       && initCipher(mCipher!!, DEFAULT_KEY_NAME)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM