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.
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.
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.