[kotlin] Kotlin Ternary Conditional Operator

TASK:

Let's consider the following example:

if (!answer.isSuccessful()) {
    result = "wrong"
} else {
    result = answer.body().string()
}
return result

We need the following equivalent in Kotlin:

return ( !answer.isSuccessful() ) ? "wrong" : answer.body().string()


SOLUTION 1.a. You can use if-expression in Kotlin:

return if (!answer.isSuccessful()) "wrong" else answer.body().string()

SOLUTION 1.b. It can be much better if you flip this if-expression (let's do it without not):

return if (answer.isSuccessful()) answer.body().string() else "wrong"


SOLUTION 2. Kotlin’s Elvis operator ?: can do a job even better:

return answer.body()?.string() ?: "wrong"


SOLUTION 3. Or use an Extension function for the corresponding Answer class:

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


SOLUTION 4. Using the Extension function you can reduce a code thanks to Elvis operator:

return answer.bodyOrNull()?.string() ?: "wrong"


SOLUTION 5. Or just use when operator:

when (!answer.isSuccessful()) {
    parseInt(str) -> result = "wrong"
    else -> result = answer.body().string()
}