首页 > 解决方案 > 如何处理来自 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 ?: ""

但这仍然无法编译。

标签: kotlinkotlin-null-safety

解决方案


将其更改为(因为它无法id从 null 对象中获取 ,除非您再次将其作为 nullable ( String?) 处理):

val companyId = companies.find { it.name == "IBM" }?.id ?: ""

如果您确定有一家名为“IBM”的公司可以使用!!(不推荐):

val companyId = companies.find { it.name == "IBM" }!!.id

此外


推荐阅读