Home > Net >  Kotlin safe calls(.?) vs null chekcs(!!)
Kotlin safe calls(.?) vs null chekcs(!!)

Time:05-26

Hi guys I was doing a little bit of reading and playing around with the kotlin language. I still can't figure out why would anybody use null checks over safe calls?

Safe calls would just return a null value if the value is null, this won't crash your app. Null checks on the other hand would raise a nullexceptionerror if the value is null. I have tried searching for the reason to use one over the other, but I can't find any resource about that.

Is there a reason to use safe calls over null checks and vice-versa?

CodePudding user response:

Null checks(!!) are used when you are completely certain that a variable is not null. It can be useful for example to avoid additional checks with if statement or let() function. If you have just a little doubt use safe calls(.?).

Null checks(!!) also used for interoperability with the Java language. For example if some Java library returns an object, Kotlin considers it as nullable, but if you are certain and library docs says that the object can't be null, so you can use Null checks(!!).

CodePudding user response:

Suppose you are fetching some data with api call of Movie data (movie_name, language, length, subtitles), and you are showing that info in list, if variable life subtitles is not present or having null value, you can use movie?.subtitles to variable if its null or not before you assign it to any text view,

For !! Operator, Suppose you define one Multithreading task where one variable like reader is running, if that is null at runtime then you can throw runtime exception

  • Related