Yao
Yao

Reputation: 709

kotlin inverse boolean safe casting

Let's say I have an object Response. Now I would like to check a boolean variable, success, under Response and do an early return is response is not successful.

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

Now I would like to use Kotlin's null safety check like following

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

If I'm not wrong, if either response or success is null we'll return true inside the if condition. However, if response.success is not null and equals to true, we will still return from the function, which is not what I want . How do I correct this condition ?

Upvotes: 4

Views: 4111

Answers (2)

user2808624
user2808624

Reputation: 2530

Quite old question, but I just stumbled over it. The following may be the shortest if clause:

if (response?.success != true) {
   //There is either no response, or it was not successful
}

Upvotes: 0

pt2121
pt2121

Reputation: 11880

I think you have to do

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

which is equivalent to your java version.

but note: if the null check version is easier to read. You can use that in Kotlin too

you can also flip the condition

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

see the Elvis operator doc for more info

Upvotes: 7

Related Questions