Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 464
Yao Avatar asked Mar 07 '23 15:03

Yao


1 Answers

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

like image 163
pt2121 Avatar answered Mar 24 '23 03:03

pt2121