我正在使用下面的代码-
editText.text.toString().isNullOrEmpty()
我收到以下 lint 警告 -
Call on not-null type may be reduced
当我右键单击 lint 警告时,它会显示 -
Change call to isEmpty
当我检查代码时-
@Nullable public Editable getText() {
if (Build.VERSION.SDK_INT >= 28) {
return super.getText();
}
// A bug pre-P makes getText() crash if called before the first setText due to a cast, so
// retrieve the editable text.
return super.getEditableText();
}
这意味着 editText.text
可以为空
/**
* Returns a string representation of the object. Can be called with a null receiver, in which case
* it returns the string "null".
*/
public fun Any?.toString(): String
这意味着toString()
可以返回null
那么ediText.text.toString().isEmpty()
如何是更好的选择,因为它可以抛出空指针异常?
最佳答案
当您调用toString()
时,结果字符串永远不会为空(因此,isNullOrEmpty()
== isEmpty
) - 任何空值值更改为字符串 "null"
。
由于这不是您想要检查的内容,因此您应该停止使用 toString()
- 只需直接使用 isNullOrEmpty()
即可:
editText.text.isNullOrEmpty()
关于android - 对非空类型的调用可能会减少-更改对 isEmpty 的调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56604120/