Search code examples
kotlinkotlin-null-safety

How to handle null return from Kotlin's find function?


I have a list of objects, for example:

val companies = listOf(
        Company(id = "1", name = "IBM"), 
        Company(id = "2", name = "Apple"))

Next, I want to find an object from this list by name condition and get the value of an id field of the object found. So, I'm using find function calling on the list:

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

But this one doesn't compile with Only safe or non-call calls are allowed on a nullable receiver. So, how should I handle the possible null return from find? I tried with an Elvis operator to return an empty String otherwise, like:

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

But that still doesn't compile.


Solution

  • Change it to (because it cannot get the id from a null object unless you handle it as nullable (String?) again):

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

    If you are sure that there is a company with name "IBM" you can use !! (not recommended):

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

    further more