avatarGabriel Shanahan

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

3213

Abstract

t="300" width="800"> </div> </div> </figure></iframe></div></div></figure><h1 id="4672">The safe call operator</h1><p id="3388">Take a look at this again:</p><div id="d5a8"><pre>println(<span class="hljs-keyword">if</span>(nullableString != <span class="hljs-literal">null</span>) nullableString.length <span class="hljs-keyword">else</span> <span class="hljs-literal">null</span>)</pre></div><p id="d634">This is such a common pattern that Kotlin defines the safe call operator <code>?.</code> which achieves the same thing:</p><div id="0633"><pre>println(nullableString?.length)</pre></div><p id="cb42">The expression <code>x?.y</code> evaluates to <code>x.y</code> when <code>x</code> is not <code>null</code>, and <code>null</code> otherwise. It is equivalent to <code>if(x != null) x.y else null</code></p><h1 id="4a4f">The elvis operator</h1><p id="30aa">Often, we would like to control the “fallback” value of the code we were just discussing, for instance:</p><div id="f9df"><pre>println(<span class="hljs-keyword">if</span>(nullableString != <span class="hljs-literal">null</span>) nullableString.length <span class="hljs-keyword">else</span> <span class="hljs-number">0</span>)</pre></div><p id="deab">Kotlin has the <i>elvis</i> operator <code>?:</code>, which when combined with <code>?.</code> achieves exactly that:</p><div id="d2cf"><pre>println(nullableString?.length ?: <span class="hljs-number">0</span>)</pre></div><p id="2d7f">The expression <code>x ?: y</code> evaluates to <code>x</code> if <code>x</code> is not <code>null</code>, and <code>y</code> otherwise. It is equivalent to <code>if(x != null) x else y</code></p><h1 id="c7b0">The bang-bang operator</h1><p id="d609">There are situations where we know an argument isn’t <code>null</code>, even though the compiler can’t prove it:</p> <figure id="64ad"> <div> <div> <img class="ratio" src="http://placehold.it/16x9"> <iframe class="" src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2FjJx1FhiZy%3Ffrom%3D5%26to%3D10&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2FjJx1FhiZy%3Ffrom%3D5%26to%3D10&amp;image=https%3A%2F%2Fplay.kotlinlang.org%2Fassets%2Fog-image.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" allowfullscreen="" frameborder="0" height="300" width="800"> </div> </div> </figure></iframe></div></div></figure><p id="e682">To deal with these situations, Kotlin introduces the not-null-assertion operator <code>!!</code>, often called the bang-bang operator:</p><div id="9870"><pre><span class="hljs-comment">// This works</span> <span class="hljs-keyword">val</span> result2: <span class="hljs-built_in">Int</span> = getFirstPositiveInt(listOf(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>))!!</pre></div><p id="e345">As in many religions, it is recommended to abstain from bang-banging, and only bang-bang when you really have to. Double-banging a <code>null</code> value throws a <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/

Options

NullPointerException.html">NPE</a>.</p><h1 id="ae00">Exercises</h1><p id="ace7">Implement <code>canBangBangKotlin()</code> in the same spirit as <code>canBangBangJava()</code>. Use the operators we just introduced.</p> <figure id="98f6"> <div> <div> <img class="ratio" src="http://placehold.it/16x9"> <iframe class="" src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2Flk79GAZkI%3Ffrom%3D40%26to%3D52&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2Flk79GAZkI%3Ffrom%3D40%26to%3D52&amp;image=https%3A%2F%2Fplay.kotlinlang.org%2Fassets%2Fog-image.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" allowfullscreen="" frameborder="0" height="300" width="800"> </div> </div> </figure></iframe></div></div></figure><p id="ece6">Implement <code>formatPhoneKotlin()</code> in the same spirit as <code>formatPhoneJava()</code>.</p> <figure id="1161"> <div> <div> <img class="ratio" src="http://placehold.it/16x9"> <iframe class="" src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2F6oGHDnS2d%3Ffrom%3D28%26to%3D47&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2F6oGHDnS2d%3Ffrom%3D28%26to%3D47&amp;image=https%3A%2F%2Fplay.kotlinlang.org%2Fassets%2Fog-image.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" allowfullscreen="" frameborder="0" height="300" width="800"> </div> </div> </figure></iframe></div></div></figure><p id="880d">Implement <code>humanStrKotlin()</code> in the same spirit as <code>humanStrJava()</code>. When you’re finished, take a look at the difference between the two and enjoy the feeling.</p> <figure id="7bdc"> <div> <div> <img class="ratio" src="http://placehold.it/16x9"> <iframe class="" src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2FBTsfQCoti%3Ffrom%3D58%26to%3D93&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2FBTsfQCoti%3Ffrom%3D58%26to%3D93&amp;image=https%3A%2F%2Fplay.kotlinlang.org%2Fassets%2Fog-image.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" allowfullscreen="" frameborder="0" height="300" width="800"> </div> </div> </figure></iframe></div></div></figure><p id="7687">Go back to <a href="https://readmedium.com/string-templates-92eb82841cbb">String Templates</a>, jump to the <a href="https://readmedium.com/table-of-contents-c52573cfa291">Table of Contents</a>, or continue to <a href="https://readmedium.com/types-142c319e5923">Types</a>.</p><figure id="8ecd"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*biBSB579iezsNvEQ_NMLBg.png"><figcaption><a href="https://www.etnetera.cz/prace-u-nas?utm_source=medium&amp;utm_medium=GabrielShanahan&amp;utm_campaign=KotlinPrimer&amp;utm_content=join-our-team&amp;utm_term=KotlinPrimer#pozice">Join me in Etnetera</a></figcaption></figure></article></body>

Nullability

The concept of nullability in Kotlin — nullable and non-nullable types, along with the safe-call, elvis and bang-bang operators.

— — — — — — — — — — — — — — —

THE CURRENT VERSION OF THIS ARTICLE IS PUBLISHED HERE.

— — — — — — — — — — — — — — —

Tags: #KOTLIN FEATURE #EXERCISE

This article is part of the Kotlin Primer, an opinionated guide to the Kotlin language, which is indented to help facilitate Kotlin adoption inside Java-centric organizations. It was originally written as an organizational learning resource for Etnetera a.s. and I would like to express my sincere gratitude for their support.

It is recommended to read the Introduction before moving on. Check out the Table of Contents for all articles.

The purpose of nullable types is to explicitly designate places where null values are allowed. This has two benefits:

  1. the compiler forces us to deal with potential null values and prevent NPE's
  2. the compiler guarantees that expressions of a non-nullable type cannot be null, saving us from writing inordinate amounts of defensive code everywhere
  • Every Kotlin type T has a nullable variant T?, e.g. Int and Int?
  • Expressions of type T can never contain null
  • Expressions of type T? can contain null

If you’re using IDEA, select any expression and use this shortcut to display its type. This is incredibly useful, and I encourage you to use it liberally.

The safe call operator

Take a look at this again:

println(if(nullableString != null) nullableString.length else null)

This is such a common pattern that Kotlin defines the safe call operator ?. which achieves the same thing:

println(nullableString?.length)

The expression x?.y evaluates to x.y when x is not null, and null otherwise. It is equivalent to if(x != null) x.y else null

The elvis operator

Often, we would like to control the “fallback” value of the code we were just discussing, for instance:

println(if(nullableString != null) nullableString.length else 0)

Kotlin has the elvis operator ?:, which when combined with ?. achieves exactly that:

println(nullableString?.length ?: 0)

The expression x ?: y evaluates to x if x is not null, and y otherwise. It is equivalent to if(x != null) x else y

The bang-bang operator

There are situations where we know an argument isn’t null, even though the compiler can’t prove it:

To deal with these situations, Kotlin introduces the not-null-assertion operator !!, often called the bang-bang operator:

// This works
val result2: Int = getFirstPositiveInt(listOf(1, 2, 3))!!

As in many religions, it is recommended to abstain from bang-banging, and only bang-bang when you really have to. Double-banging a null value throws a NPE.

Exercises

Implement canBangBangKotlin() in the same spirit as canBangBangJava(). Use the operators we just introduced.

Implement formatPhoneKotlin() in the same spirit as formatPhoneJava().

Implement humanStrKotlin() in the same spirit as humanStrJava(). When you’re finished, take a look at the difference between the two and enjoy the feeling.

Go back to String Templates, jump to the Table of Contents, or continue to Types.

Join me in Etnetera
Kotlin
Java
Programming
Null Safety
Learning
Recommended from ReadMedium