android - 可以减少对非空类型的调用 - 更改对 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()
更好的选择是什么,因为它可以抛出空指针异常?
解决方案
当您调用toString()
时,生成的 String 永远不会为 null(因此isNullOrEmpty()
== isEmpty
) - 任何 null 值都会更改为 string "null"
。
由于这不是您要检查的内容,因此您应该停止使用toString()
- 直接使用isNullOrEmpty()
:
editText.text.isNullOrEmpty()
推荐阅读
- ios - 如何让 SwiftUI View 扩大可用空间?
- sql-server - SQL Server 2019,使用 T-SQL,我正在尝试从订单表中的订单号列中提取“-”和“/”之间的数据值
- java - Java Spring Boot 单元测试服务状态不为每个单元测试刷新
- python - 如何将子词典移动到另一个词典?
- java - Hibernate INSERT 未出现在数据库“JDBC 事务标记为仅回滚”中
- azure-devops - 能否以编程方式为 Azure DevOps 发布管道中的变量设置可覆盖的默认值?
- javascript - 我正在构建一个动态生成选项卡的组件,无法弄清楚如何传入标题以动态命名这些选项卡
- python - 对于每个 String S,打印 的偶数索引字符,后跟一个空格,然后是 的奇数索引字符
- python - 在 Python 中,如何将单词与列表相关联,然后从列表中随机打印一个值?
- sql - 如何添加一行以检查它是否存在?