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

Viewed 58

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
}
2 Answers

So why does Kotlin's if statement require a null else part?

Because the compiler does not know that you want to return null in the else branch. For all it knows, you might want to do something else, such as return a random number, or return some default value, or throw an exception.

But in the above situation, we can write the same code without the ?: null part and the compiler will automatically assign null value.

That is because the safe call (?.) evaluates to null if the receiver is null.

I know your question is more about kolin rather than finding a way of doing something like that, but maybe takeIf is close to what you want.

return response.takeIf { it.isSuccessful() }?.body
Related