Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon

How to avoid NullPointerExceptions in Kotlin [Video]

Save for later
  • 2 min read
  • 20 Oct 2018

article-image
Kotlin has been rapidly growing in popularity in recent times. Some say it is even poised to take over Java, as the next universal programming language. This is because Kotlin is interoperable with Java. It is possible to write applications containing both Java and Kotlin code, calling one from the other. Secondly, while being interoperable, Kotlin code is far superior to Java code. Like Scala, Kotlin uses type inference to cut down on a lot of boilerplate code and makes it concise. However, unlike Scala, Kotlin code is easy to read and understand, even for someone who may not know Kotlin.

Moreover, Kotlin is excellent in addressing the NullPointerException which causes a lot of checks in Java programs. In Kotlin, developers can avoid the dreaded NullPointerException by properly handling optional types. In this video, Nigel Henshaw shows how to avoid NullPointerExceptions in Kotlin.

This clip is taken from the course Kotlin - Tips, Tricks, and Techniques by Nigel Henshaw. With this course, you will discover new possibilities with Kotlin and improve your app development process.

How to avoid NullPointerExceptions?


There are three ways to avoid NullPointerExceptions. These include:

  • Use the Elvis operator for handling null values. The Elvis operator makes the code more concise and readable
  • Use safe casts for avoiding ClassCastExceptions. Instead, ClassCastExceptions can be replaced with null.
  • Using safe casts with Elvis operator. The Elvis operator can be combined with a safe cast for returning null values.
  • Unlock access to the largest independent learning library in Tech for FREE!
    Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
    Renews at €18.99/month. Cancel anytime


Watch the video to walk through each of the methods using code examples. If you liked the video, don’t forget to check out the comprehensive course Kotlin - Tips, Tricks, and Techniques, packed with step-by-step instructions, working examples, and helpful tips and techniques on working with Kotlin.

About the author


Nigel Henshaw is a mobile software developer. He loves to share his knowledge through his YouTube channel and website. Nigel has worked in the UK, Scotland, and Japan. He has held jobs as a software engineer, consultant, project manager, and general manager of a remote development site.

Implementing Concurrency with Kotlin [Tutorial]

KotlinConf 2018: Kotlin 1.3 RC out and Kotlin/Native hits beta

Kotlin 1.3 RC1 is here with compiler and IDE improvements