Kotlin reverse boolean safe casting

Say I have a Response object. Now I would like to check the boolean variable, success in the response and make an early return - the answer was unsuccessful.

if(response == null || !response.success){
   return;
} //Java version

Now I would like to use the Kotlin security check as shown below.

if(response?.success ?: true){
    return
}

If I am not mistaken, if any answer or success is zero, we will return true in the if condition. However, if response.success is not NULL and true, we will still return from the function, which I don't want. How to fix this condition?

+4
source share
1 answer

I think you need to do

if(!(response?.success ?: false)){
    return; // null or failed
}

which is equivalent to your java version.

but note: if the control version is nulleasier to read. You can use this in Kotlin too

response?.success?.let {
  // do something when success
}

. Elvis

+3

Source: https://habr.com/ru/post/1689027/


All Articles