首页 > 解决方案 > 可以减少对非空类型的调用 - 更改对 isEmpty 的调用

问题描述

我正在使用以下代码-

editText.text.toString().isNullOrEmpty()

我得到低于皮棉警告 -

对非空类型的调用可能会减少

当我右键单击 lint 警告时,它说-

更改对 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()更好的选择是什么,因为它可以抛出空指针异常?

标签: androidkotlinnullpointerexceptionandroid-edittext

解决方案


当您调用toString()时,生成的 String 永远不会为 null(因此isNullOrEmpty()== isEmpty) - 任何 null 值都会更改为 string "null"

由于这不是您要检查的内容,因此您应该停止使用toString()- 直接使用isNullOrEmpty()

editText.text.isNullOrEmpty()

推荐阅读