kotlin - 如何处理来自 Kotlin 的 find 函数的 null 返回?
问题描述
我有一个对象列表,例如:
val companies = listOf(
Company(id = "1", name = "IBM"),
Company(id = "2", name = "Apple"))
接下来,我想通过name
条件从这个列表中找到一个对象,并获取找到的对象的一个id
字段的值。所以,我find
在列表中使用函数调用:
val companyId = companies.find { it.name == "IBM" }.id
但是这个不能编译在可以为空的接收器上只允许安全或非调用调用。那么,我应该如何处理可能的null
回报find
?我尝试使用 Elvis 运算符返回一个空字符串,否则,例如:
val companyId = companies.find { it.name == "IBM" }.id ?: ""
但这仍然无法编译。
解决方案
将其更改为(因为它无法id
从 null 对象中获取 ,除非您再次将其作为 nullable ( String?
) 处理):
val companyId = companies.find { it.name == "IBM" }?.id ?: ""
如果您确定有一家名为“IBM”的公司可以使用!!
(不推荐):
val companyId = companies.find { it.name == "IBM" }!!.id
推荐阅读
- node.js - 如何使用用户名和密码获取 Instagram cookie?
- html - 未处理的异常:FormatException:无效的 radix-10 数字(在字符 1)
- java - 你如何只返回 x 条记录
- ruby-on-rails - 尝试 Capistrano 部署时出现 Bundler 错误
- perl - 如何使用 Getopt::Long 将选项存储在复杂哈希中
- python - “ValueError:...与图层不兼容:输入形状的预期轴 -1 的值为 8,但接收到的输入形状为 (None, 7, 169)”
- assembly - 关于交叉编译时汇编代码错误的问题
- javascript - 反应:在传递给类构造函数的回调函数中使用状态不使用最新版本的状态
- python-3.x - Python BeautifulSoup“奇怪”错误
- c - 为什么以下带有字符串的代码在从函数调用时会生成总线错误?