[英]Null check in if conditions
I have this code in Java 我在Java中有此代码
return mFingerprintManager.hasEnrolledFingerprints() &&
createKey(DEFAULT_KEY_NAME, true) &&
initCipher(mCipher, DEFAULT_KEY_NAME);
which I have converted to Kotlin as shown here 我已将其转换为Kotlin,如下所示
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? 有没有更好的方式编写Kotlin代码,这样更简洁? Variable mCipher is defined as
变量mCipher定义为
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. 如果接收器不为null,则在可为null的接收器上返回函数的结果,否则为null。
Combining this with .apply
we can write: 将此与
.apply
结合在一起,我们可以编写:
[..] && mCipher?.apply { initCipher(this, DEFAULT_KEY_NAME) } != null
[..]
&& mCipher?.apply { initCipher(this, DEFAULT_KEY_NAME) } != null
Wait, why can't you copy-paste the Java code to Kotlin? 等一下,为什么不能将Java代码复制粘贴到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. 如果
initCipher(...)
可以将null
作为其参数进行处理,则无需在将其传递给方法之前检查mCipher
。
Update: 更新:
It seems that you've converted initCipher
from Java to Kotlin, and now it can't accept null
as its argument. 似乎您已经将
initCipher
从Java转换为Kotlin,现在它不能接受null
作为其参数了。 Then, assuming you don't have a concurrent access to mCipher
, add a null-assertion !!
然后,假设您没有对
mCipher
的并发访问mCipher
,请添加一个null断言!!
to the code: 代码:
return mFingerprintManager.hasEnrolledFingerprints()
&& createKey(DEFAULT_KEY_NAME, true)
&& initCipher(mCipher!!, DEFAULT_KEY_NAME)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.