Home > other >  Kotlin concatenate checking an nullable key and nullable entry
Kotlin concatenate checking an nullable key and nullable entry

Time:09-26

I have a function that takes a nullable String key and try use it to retrieve an entry from a registry, if key is null or entry not found, run some fallback logic.

Is it possible to collapse the two fallbackLogic() call into one block?

fun getEntry(key: String?) {
  key?.let { nonNullKey->
    Registry.retrieve(nonNullKey)?.let { nonNullEntry->
      nonNullEntry.doStuff()
    } ?: run {
      fallbackLogic() // if key is nonNull, but entry is null
    }
  }?: run {
    fallbackLogic() // if key is null
  }

}


CodePudding user response:

Maybe I miss something, but I think you really overcomplicated it. Is this what you need?

key?.let { Registry.retrieve(it) }
    ?.doStuff()
    ?: fallbackLogic()

Alternatively, you can write the first line as:

key?.let(Registry::retrieve)
  • Related