android – What does the "!!" operator mean in Kotlin?-ThrowExceptions

Exception or error:

I’m reading this guide from Google for Android and they have the snippet bellow.

What does the !! do in userDao.save(response.body()!!)?

private fun refreshUser(userId: String) {
   // Runs in a background thread.
   executor.execute {
       // Check if user data was fetched recently.
       val userExists = userDao.hasUser(FRESH_TIMEOUT)
       if (!userExists) {
           // Refreshes the data.
           val response = webservice.getUser(userId).execute()

           // Check for errors here.

           // Updates the database. The LiveData object automatically
           // refreshes, so we don't need to do anything else here.
           userDao.save(response.body()!!)
       }
   }
}
How to solve:

This is used to convert an expression to non-null and throw a KotlinNullPointerException if the result is null. So in this usage, it will only save the response’s body was not null, otherwise an exception will be thrown.

See here for more information.

Leave a Reply

Your email address will not be published. Required fields are marked *