Search code examples
kotlinnull-checkkotlin-null-safety

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

  • 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