

For `val`s, go with that approach, no questions.

Verdict? Well, the OG `if` checks are straight up a better fit for the use case of a null check. And the Kotlin code is still cleaner compared to Approach 1.įor nullable (and mutable) vars with the scope functions, while adding things which are not needed, do improve the code quality, `with` being a slightly more efficient than others. Well, before you get too excited, it’s only one less temporary variable in the decompiled code, but hey, it’s something. Let’s use the one mentioned below for this discussion. We’ll go through 2 different situations, use different approaches, and to keep a check on the underlying complexity we will also look at their decompiled Java versions 😏.īut first, we need a method that takes a non-nullable value. Here’s one example, well they’re not wrong. But some people can argue that let is just overkill for null checks because of some unnecessary processing involved. Even the official documentation suggests that let is an excellent way to tackle null checks. Now before you yell, “USE LET, USE LET, SCOPE FUNCTIONS FTW!!!”. Some dread it, to others it sounds very natural. In the next tutorial we will discuss about regular expression in Kotlin.Kotlin developers, I know we’ve all been there, checking if a value is null before using it.

Null safety is an important feature of Kotlin and it saves us from Null pointer exception. In this tutorial we discussed about Null safety in Kotlin. So, the !! operator should be avoided as much as possible. Let us see a small example in Java where NullPointerException occurs: public class Student ") // Throws NullPointerException If we try to use this variable then we will get NullPointerException or NPE. In programming world when a variable doesn't refer to anything then it is considered as null. In this tutorial we will discuss about one of the most important features of Kotlin: Null Safety.
