可以减少非空类型的调用-将调用更改为isEmpty

时间:2019-06-14 19:28:02

标签: android kotlin nullpointerexception android-edittext

我正在使用以下代码-

editText.text.toString().isNullOrEmpty()

我得到了不起毛的警告-

  

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

当我右键单击棉绒警告时,它会显示-

  

将呼叫更改为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()是更好的选择,因为它会引发空指针异常?

1 个答案:

答案 0 :(得分:1)

调用toString()时,结果字符串永远不会为空(因此isNullOrEmpty() == isEmpty)-任何空值都将更改为字符串"null"。 / p>

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

editText.text.isNullOrEmpty()