Kotlin / Kotlin Basics

Working with Null Safety in Kotlin

In this tutorial, we will explore Kotlin's null safety feature. We will learn how to declare nullable and non-nullable types, and how to handle null pointer exceptions.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explores the foundational concepts in Kotlin, including variables, data types, and operators.

Kotlin Null Safety Tutorial

1. Introduction

Goal

This tutorial aims to provide an in-depth look into the null safety feature in Kotlin, a significant improvement from the Java programming language.

Learning Outcomes

By the end of this tutorial, you will understand how to declare nullable and non-nullable types, how to handle null pointer exceptions, and best practices for using null safety in Kotlin.

Prerequisites

  • Basic understanding of Kotlin syntax and data types
  • Familiarity with the concept of nullability in programming

2. Step-by-Step Guide

In Kotlin, every variable must be declared either as nullable or non-nullable. A nullable variable can hold a null value, whereas a non-nullable variable cannot.

Non-Nullable Types

By default, variables are non-nullable in Kotlin. Here's an example:

var name: String = "Kotlin"

If you try to assign null to this variable, it will result in a compile-time error:

name = null // Compilation error

Nullable Types

To declare a variable as nullable, append a question mark to the type:

var name: String? = "Kotlin"

Now, you can assign null to this variable:

name = null // No error

Null Safety Operators

Kotlin provides several operators for safely dealing with nullable types:

  • Safe Call Operator ?. : It returns null if used on a null reference.
  • Non-null Assertion Operator !! : Converts nullable type to a non-nullable type, and throws a NullPointerException if the nullable type holds a null value.
  • Elvis Operator ?: : Returns the left-hand expression if it's non-null; otherwise, it returns the right-hand expression.

3. Code Examples

Example 1: Safe Call Operator

var name: String? = null

// Use safe call operator
println(name?.length) // It will print 'null' because name is null.

Example 2: Non-null Assertion Operator

var name: String? = null

// Use non-null assertion operator
println(name!!.length) // It will throw NullPointerException because name is null.

Example 3: Elvis Operator

var name: String? = null

// Use Elvis operator
println(name?.length ?: "Name is null") // It will print 'Name is null' because name is null.

4. Summary

We've learned that Kotlin provides a robust system for avoiding null pointer exceptions. By distinguishing nullable and non-nullable types, and providing helpful operators, Kotlin makes your code safer and more expressive.

5. Practice Exercises

  1. Declare a nullable String variable and a non-nullable Int variable. Try assigning null to both of them and observe the results.

  2. Experiment with the safe call operator, non-null assertion operator, and Elvis operator. Create different scenarios to understand their functionality.

Solutions

var nullableString: String? = "Kotlin"
nullableString = null // No error

var nonNullableInt: Int = 10
nonNullableInt = null // Compilation error

2.

var name: String? = null

// Safe call operator
println(name?.length) // prints null

// Non-null assertion operator
// println(name!!.length) // Uncommenting this will throw NullPointerException

// Elvis operator
println(name?.length ?: "Name is null") // prints 'Name is null'

Continue exploring more about Kotlin's null safety features from the official Kotlin documentation.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

Use tool

PDF to Word Converter

Convert PDF files to editable Word documents.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

CSV to JSON Converter

Convert CSV files to JSON format and vice versa.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help