Null Safety

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
July 16, 2023

Kotlin Null Safety

Introduction

Kotlin is a statically-typed programming language designed for the Java Virtual Machine (JVM) by JetBrains. One of Kotlin's standout features is its null safety, which helps developers avoid the dreaded null pointer exceptions commonly found in many programming languages.

Null References

In Kotlin, null is not a valid value for most variables by default. To allow null values, we must explicitly declare a variable as nullable using the nullable type modifier "?". This forces developers to handle null references at compile-time, reducing the likelihood of runtime crashes due to null pointer exceptions.

Safe Calls

Safe calls in Kotlin allow us to safely access properties and call methods on nullable objects without risking a null pointer exception. Using the safe call operator "?." after a nullable variable ensures that the expression is only evaluated if the variable is not null. If the variable is null, the expression returns null instead of throwing an exception.

Example

Let's consider the following example where we have a nullable variable name of type String?:


val name: String? = "John Doe"
val length = name?.length

In the above code snippet, the safe call operator "?." ensures that the length property is only accessed if name is not null. If name is null, the length variable will also be null.

Elvis Operator

The Elvis operator, denoted by "?:", provides an alternative value to be used when the expression preceding it is null. The Elvis operator comes in handy when assigning a default value to a nullable variable if the original value is null.

Example

Let's modify our previous example to include the Elvis operator:


val name: String? = null
val length = name?.length ?: 0

In the above code, if name is null, the Elvis operator assigns a default value of 0 to length. This ensures that length is always assigned a non-null value, avoiding any potential null pointer exceptions.

Summary

Kotlin's null safety features, such as safe calls and the Elvis operator, provide a more robust and safer programming experience. By enforcing null checks at compile-time, Kotlin helps developers write code that is less prone to null pointer exceptions, leading to more reliable and resilient applications.