Ternary operator

If you happen to find yourself writing this kind of code often, then you can consider defining an extension function like this one for the corresponding Response class (whatever it is the actual class you are using):

fun Response.bodyOrNull(): Body? = if (isSuccessful()) body() else null

with this extension function your code reduces to

return response.bodyOrNull()?.string() ?: "fail"
8 Likes