samedi 4 juillet 2020

Is there an idiomatic way to deal with null value in if else branch?

I'm kind of thinking if there is a cleaner way to express this code.

return if (response.isSuccessful()) {
    response.body
else null

What I'm referring to here is the else null part. An almost similar statement in Kotlin would be

return response?.let {
    it.body
} ?: null

But in the above situation, we can write the same code without the ?: null part and the compiler will automatically assign null value. So why does Kotlin's if statement require a null else part?

return if (response.isSuccessful()) {
    response.body
}

Aucun commentaire:

Enregistrer un commentaire