Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何处理来自Kotlin';s查找函数?_Kotlin_Kotlin Null Safety - Fatal编程技术网

如何处理来自Kotlin';s查找函数?

如何处理来自Kotlin';s查找函数?,kotlin,kotlin-null-safety,Kotlin,Kotlin Null Safety,我有一个对象列表,例如: val companies = listOf( Company(id = "1", name = "IBM"), Company(id = "2", name = "Apple")) 接下来,我想通过name条件从这个列表中找到一个对象,并获取找到的对象的id字段的值。因此,我使用find函数调用列表: val companyId = companies.find { it.name == "IBM" }.id 但是这个函数不能编译

我有一个对象列表,例如:

val companies = listOf(
        Company(id = "1", name = "IBM"), 
        Company(id = "2", name = "Apple"))
接下来,我想通过
name
条件从这个列表中找到一个对象,并获取找到的对象的
id
字段的值。因此,我使用
find
函数调用列表:

val companyId = companies.find { it.name == "IBM" }.id
但是这个函数不能编译,只能在可为空的接收器上进行安全或非调用调用。那么,我应该如何处理从
find
返回的可能的
null
?我尝试使用Elvis运算符返回空字符串,否则,如:

val companyId = companies.find { it.name == "IBM" }.id ?: ""
但这仍然无法编译。

将其更改为(因为它无法从空对象获取
id
,除非您再次将其作为可空(
字符串?
)处理):

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


请注意,如果找到该公司且其
id
null
,则这也将返回
val companyId = companies.find { it.name == "IBM" }?.id ?: ""
val companyId = companies.find { it.name == "IBM" }!!.id