【问题标题】:Kotlin assumes value to be not nullKotlin 假定 value 不为 null
【发布时间】:2022-09-30 21:49:45
【问题描述】:

我有下面的代码从列表中选择第一个项目,其中项目的姓氏字段值不应该是UNKNOWNMISSING

val userLastName = someList
      .first { it.lastName != \"UNKNOWN\" && it.lastName != \"MISSING\" }
      .lastName

现在 Intellij 说字段 userLastName 永远不能为空。为什么?

如果列表中的所有对象的lastName 字段值为UNKNOWNMISSING,那么userLastName 变量将为空,对吗?

我试图更改代码以使用 null 安全运算符:

val userLastName = someList
          .first { it.lastName != \"UNKNOWN\" && it.lastName != \"MISSING\" }
          ?.lastName

但我收到以下警告:

Safe call on a non-null receiver will have nullable type in future releases

    标签: kotlin


    【解决方案1】:

    .first 函数要求至少有一个元素与谓词匹配。如果没有找到匹配的元素,它会抛出异常。

    如果您想在没有元素匹配时返回null,您可以使用.find 而不是.first

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-03
    相关资源
    最近更新 更多