'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 ?
Solution 1:[1]
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
}
Solution 2:[2]
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
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Wahib Ul Haq |
Solution 2 | user2808624 |