<p>This tutorial is about <span style="color: #000000;"><strong>Null Safety</strong></span> in Kotlin.</p>
<p><span style="color: #008000;"><strong>Null Safety</strong></span> in Kotlin is to eliminate the risk of occurrence of <strong><span style="color: #008000;">NullPointerException</span></strong> from code.</p>
<p class="p1">One of the most common pitfalls in many programming languages, including Java, is that accessing a member of a null reference will result in a null reference exception. In Java this would be the equivalent of a <strong><span style="color: #0000ff;">NullPointerException or NPE</span></strong>.</p>
<p class="p1">Let&#8217;s understand with simple example in Java where <strong>NullPointerException</strong> occurs:</p>
<p><strong><span style="color: #0000ff;">Example:</span></strong></p>
<pre>class Student {
 public static void main(String[] args) {
 String name = null;
 System.out.println("Student name : " + name);
 System.out.println("Student name (Uppercase): " + name.toUpperCase());
 }
}</pre>
<p><strong><span style="color: #0000ff;">Output:</span></strong></p>
<pre>Student name : null
Exception in thread "main" java.lang.NullPointerException
at Student.main(Exp.java:6)</pre>
<p>Kotlin&#8217;s comes with <strong>null safety</strong> to eliminate <strong>NullPointerException&#8217;s</strong> from our code.</p>
<h4 class="p1"><span style="color: #000080;"><b>Nullable and Non-Null References</b></span></h4>
<p class="p2">In Kotlin, the type system differentiates between two types of references:</p>
<ol class="ol1">
<li class="li2"><span style="color: #0000ff;"><b>Nullable Reference:</b></span> These references <strong><span style="color: #008000;">can hold</span></strong> <span style="color: #008000;"><strong>null</strong></span> values.</li>
<li class="li2"><span style="color: #0000ff;"><b>Non-Null Reference:</b></span> These references <strong><span style="color: #008000;">can&#8217;t hold</span> <span style="color: #008000;">null</span></strong> values.</li>
</ol>
<p class="p1">In Kotlin, all variables are non-nullable by default. We cannot assign a <strong><span style="color: #008000;"><i>null</i></span></strong> value to a variable because it’ll throw a compilation error(<strong>NPE</strong>):</p>
<p class="p2"><span style="color: #0000ff;"><strong>Example:</strong></span></p>
<pre>fun main() {
 var name:String = "Arun"
 var name:String = null <strong><span style="color: #008000;">// COMPILATION ERROR</span></strong>
}</pre>
<p><strong><span style="color: #0000ff;">Output:</span></strong></p>
<pre>Error:(6, 27) Kotlin: Null can not be a value of a non-null type String</pre>
<p class="p1">Here, by default compiler considers <strong><span style="color: #008000;">name</span></strong> variable as a Non-Null reference. So, we cannot assign <span style="color: #0000ff;"><strong>null</strong></span> to it.</p>
<p class="p1"><strong class="jg ks">To define a nullable variable, we must append a question mark(?) to the type declaration:</strong></p>
<pre>fun main() {
 var name: String? = null <span style="color: #008000;"><strong> // NO ERROR</strong></span>
}</pre>
<p class="p1">We can call a method or access a property on a non-nullable variable. However, in the case of nullable variables, we need to handle the null case explicitly. Otherwise, it will throw a compilation error since Kotlin knows that the variable contains null references:</p>
<pre class=" language-kotlin"><code class=" language-kotlin"><span class="token keyword">fun</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
 <span class="token keyword">var</span> name<span class="token operator">:</span>String<span class="token operator">?</span> <span class="token operator">=</span> <span class="token string">"Arun"</span>
 <span class="token function">println</span><span class="token punctuation">(</span>name<span class="token punctuation">.</span>length<span class="token punctuation">)</span> <strong><span class="token comment" style="color: #008000;"> // ERROR</span></strong>
<span class="token punctuation">}</span></code></pre>
<p><strong><span style="color: #0000ff;">Output:</span></strong></p>
<pre>Error:(7, 21) Kotlin: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?</pre>
<p>Here compiler is not allowing us to find length of the String directly because it may throw Null Pointer Exception.</p>
<h4 id="b233" class="ig ih dt ce ii ij ik il im in io ip iq ir is it iu iv iw ix iy iz ja jb jc jd eq"><span style="color: #000080;"><strong class="ax">Working With Nullable Types</strong></span></h4>
<p class="p1">Let’s look at the different ways how we can handle null references safely in Kotlin.</p>
<ul class="ol1">
<li class="li1"><strong><span style="color: #0000ff;">Check null in conditions</span></strong></li>
<li class="li1"><strong><span style="color: #0000ff;">Safe calls</span></strong></li>
<li class="li1"><strong><span style="color: #0000ff;">The Elvis operator</span></strong></li>
<li class="li1"><strong><span style="color: #0000ff;">The !! operator</span></strong></li>
</ul>
<h4 class="p2"><span style="color: #000080;"><b>Null </b></span><span style="color: #000080;"><b>Check</b></span></h4>
<p class="p1"><strong>We can use the <span style="color: #008000;">if-else</span> expression to explicitly check for nullable variables.</strong></p>
<p><strong><span style="color: #0000ff;">Example:</span></strong></p>
<pre>fun main() {
 var name:String? = "Arun"
 if (name != null)
 println(name.length)
 else 
 null
}</pre>
<p><strong><span style="color: #0000ff;">Output:</span></strong></p>
<pre>4</pre>
<p class="p1">Now compiler won&#8217;t give any error as we have already checked null condition first. It is the most basic way to deal with Nullable Reference.</p>
<h4 class="p2"><span style="color: #000080;"><b>Safe Call Operator(?.)</b></span></h4>
<p class="p1"><strong class="jg ks">Kotlin has a safe call <span style="color: #008000;">operator(?.)</span> to handle null references</strong>.</p>
<!-- WP QUADS Content Ad Plugin v. 2.0.98.1 -->
<div class="quads-location quads-ad2" id="quads-ad2" style="float:none;margin:0px;">

</div>

<p class="p1">This operator executes any action only when the reference has a non-null value. Otherwise, it returns a <span style="color: #008000;"><strong>null</strong></span> value.</p>
<p>The following expression:</p>
<pre>name?.length</pre>
<p>is equivalent to:</p>
<pre>if (name != null)
 name.length
 else
 null</pre>
<p><strong><span style="color: #0000ff;">Example:</span></strong></p>
<pre>fun main() {
 var name: String? = "Ninja"
 println("Name length: ${name?.length}")

 name = null
 println("Name length: ${name?.length}")
}</pre>
<p><strong><span style="color: #0000ff;">Output:</span></strong></p>
<pre>Name length: 5
Name length: null</pre>
<h4 class="p1"><span style="color: #000080;"><b>Using let() Method</b></span></h4>
<p class="p2">We can use the <strong><span style="color: #008000;">let()</span></strong> method along with the safe call operator to act on a non-nullable variable:</p>
<p><strong><span style="color: #0000ff;">Example:</span></strong></p>
<pre>fun main(args: Array<;String>;) {
 val cities: List<;String?>; = listOf("Kolkata", null, "Mumbai", "Delhi", null, "Banglore")
 var newlist: List<;String?>; = emptyList()
 for (city in cities) {
 city?.let {
 newlist = newlist.plus(it)
 }
 }
 println(newlist)</pre>
<p><strong><span style="color: #0000ff;">Output:</span></strong></p>
<pre>[Kolkata, Mumbai, Delhi, Banglore]</pre>
<h4 class="p1"><span style="color: #000080;"><b>Using also() Method</b></span></h4>
<p class="p2">We can use the <strong><span style="color: #008000;">also() </span></strong>method to execute additional operations like logging and printing of the non-nullable variables. <b>This method can be used in a chain with<span style="color: #008000;"> let() or run() </span>method</b>.</p>
<p class="p2">Here&#8217;s how we can use also() method along with let() method:</p>
<p><strong><span style="color: #0000ff;">Example:</span></strong></p>
<pre>fun main(args: Array<;String>;) {

 val cities: List<;String?>; = listOf("Kolkata", null, "Mumbai", "Delhi", null, "Banglore")
 var newlist: List<;String?>; = emptyList()
 
 for (city in cities) {
 city?.let {
 newlist = newlist.plus(it)
 it
 }?.also { it ->; println("$it") }
 }
 println(newlist)</pre>
<p><strong><span style="color: #0000ff;">Output:</span></strong></p>
<pre>Kolkata
Mumbai
Delhi
Banglore
[Kolkata, Mumbai, Delhi, Banglore]</pre>
<h4 class="p1"><span style="color: #000080;"><b>Using run() Method</b></span></h4>
<p class="p2">We can use the <span style="color: #008000;"><strong>run() </strong></span>method to execute some operations on a non-nullable reference. <b>This method operates using <span style="color: #0000ff;">this</span> reference and returns the value of the lambda result:</b></p>
<p><strong><span style="color: #0000ff;">Example:</span></strong></p>
<pre>fun main(args: Array<;String>;) {

 val cities: List<;String?>; = listOf("Kolkata", null, "Mumbai", "Delhi", null, "Banglore")
 var newlist: List<;String?>; = emptyList()
 for (city in cities) {
 city?.run {
 newlist = newlist.plus(this)
 this
 }?.also {it->; println("$it") }
 }
 println(newlist)</pre>
<p><strong><span style="color: #0000ff;">Output:</span></strong></p>
<pre>Kolkata
Mumbai
Delhi
Banglore
[Kolkata, Mumbai, Delhi, Banglore]</pre>
<h4></h4>
<h4 class="p1"><span style="color: #000080;"><b>Elvis Operator (?:)</b></span></h4>
<p class="p1"><b>We can use the Elvis operator(?:) to return a default value only if the original variable has a null value</b>.</p>
<p class="p1">If the left-side expression of the Elvis operator has a non-nullable value, then it is returned. Otherwise, the right-side expression is returned.</p>
<p>The following expression:</p>
<pre>name?.length ?: -1</pre>
<p>is equivalent to:</p>
<pre>if (name != null)
 name.length
 else
 -1</pre>
<p class="p2"><strong style="font-size: 16px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif;"><span style="color: #0000ff;">Example:</span></strong></p>
<pre>fun main() {
 var name: String? = "Arun"
 println("Name length: ${name?.length ?: -1}")

 name = null
 println("Name length: ${name?.length ?: -1}")
}</pre>
<p><strong><span style="color: #0000ff;">Output:</span></strong></p>
<pre>Name length: 4
Name length: -1</pre>
<p><strong>We can also use <span style="color: #0000ff;">throw</span> and <span style="color: #0000ff;">return</span> expression in the right-side expression of the Elvis operator.</strong> So instead of default values, we can throw specific exceptions in the right-side expressions of the <em class="kd"><strong><span style="color: #008000;">Elvis</span></strong> operator:</em></p>
<pre>var name: String? = null
val nameLength = name?.length ?: throw IllegalArgumentException("invalid length")</pre>
<h4 id="b6d2" class="kh ih dt ce ii kt ku eu im kv kw ex iq ey kx fa iu fb ky fd iy fe kz fg jc la eq"><strong><span style="color: #000080;">Not Null Assertion Operator ( !! )</span></strong></h4>
<p class="p2"><strong class="jg ks">We can use the not-null assertion operator(!!) to explicitly throw a NullPointerException</strong>.</p>
<p class="p2">This operator converts any reference to its non-nullable type and throws an exception if the reference has a null value.</p>
<p><strong><span style="color: #0000ff;">Example:</span></strong></p>
<pre>fun main() {
 var name: String? = "Arun"
 println("Name length: ${name!!.length}") <strong><span style="color: #008000;">// prints 4</span></strong>

 name = null
 println("Name length: ${name!!.length}") <strong><span style="color: #008000;">// Throws NullPointerException</span></strong>
}</pre>
<p><strong><span style="color: #0000ff;">Output:</span></strong></p>
<pre>Name length: 4
Exception in thread "main" kotlin.KotlinNullPointerException
at ExampleKt.main(Example.kt:44)
at ExampleKt.main(Example.kt)</pre>


