Home > database >  Kotlin assumes value to be not null
Kotlin assumes value to be not null

Time:10-01

I have the below code to pick the first item from the list where the item's lastname field value should not be UNKNOWN or MISSING.

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

Now Intellij says that the field userLastName can never be null. Why?

If the list has all objects whose lastName field value is either UNKNOWN or MISSING then the userLastName variable will be null right?

I tried to change the code to use null safe operator:

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

But I get the below warning:

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

CodePudding user response:

The .first function requires that at least one element matches the predicate. It throws an exception if no matching element is found.

If you want to instead return null when no elements match, you can use .find instead of .first.

  • Related