Table of contents
1.
Introduction
2.
Null Safety in Kotlin
3.
Dealing with NullPointerException
4.
Kotlin nullable and Non-nullable Types
5.
Filtering null values 
6.
Advance Null Safety 
6.1.
Safe Calls Operator
6.2.
Elvis Operator
6.3.
The Not Null Assertion Operator
7.
FAQs
8.
Key Takeaways
Last Updated: Mar 27, 2024

Kotlin Null Safety

Author Vivek Goswami
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

A significant issue with programming language arises when we try to access a variable with a null value. Accessing such variables leads to NullPointerException at runtime. NonNullException is highly problematic and undesirable. 

Kotlin is a modern and advanced language for android development. It offers many benefits to programmers. We see these benefits in the way Kotlin handles NullPointerException.

NullPointerException is a common problem in the case of android development with java programming. 

Null Safety in Kotlin

As mentioned earlier, NullPointerException is an issue generally faced by programmers. Hence, we need to solve this problem. A NullPointerException is a runtime exception. We come across a NullPointerException error when a program tries to use an object reference that has a null value. Kotlin Null safety aims to eliminate this error from the code. 

In Kotlin, the NullPointerException is thrown at in the following two situations only. The three situations are as follows:

  1. Forceful call: We can get a NullPointerException if we forcefully call a variable with a null value assigned to it using the not-null assertion operator.
  2. Java Interoperability: When we use external java code in Kotlin, it throws a NullPointerException. The use of external java code in Kotlin is called java interoperability. 
  3. Data Inconsistency during initialization: An uninitialized operator is available in a constructor passed and used elsewhere. It can also occur when a superclass constructor calls an open member whose implementation in the derived class uses an uninitialized state. 

Dealing with NullPointerException

Kotlin offers many successful strategies to tackle NullPointerException in programming. The techniques used are listed as follows:

  1. Kotlin Nullable and Non-Nullable Types
  2. Smart Cast
  3. Kotlin safe cast operator
  4. Elvis Operator

Let us go through these by one to understand their implementation in the code.

Kotlin nullable and Non-nullable Types

Kotlin distinguishes between references with null values and those that do not have null values. 

Example: The string data type can’t hold null values. To allow nulls in strings, we need to declare them separately. We can declare a nullable string by defining it with the reserved word  String?: 

Let us go through the code of these to understand them better.

CODE 1: Non-Nullable String in Kotlin

fun main() {
    var x: String = "Coding Ninjas"; // general initialization of variable x which is of string data type
    // general initialization automatically assigns a non-null value to the variable
    x = null; // compilation error
}

Output:

Null can not be a value of a non-null type String

However, using the same code in Java wouldn’t produce any compilation error. Instead, it would give the NullPointerException at runtime. 

CODE 2: Nullable Strings in Kotlin

fun main() {
    var y: String? = "Coding Ninjas." // Initialization of a variable that allows the string to hold null
    // values
    y = null // We do not encounter an error in this case. Nullable values are allowed.
    print(y)
}

Output:

null

If we access and operate on the variable x, it would not throw a NullPointerException. However, when variable y is accessed, the compiler would throw a runtime error that needs to be corrected.

Syntax to check this is as follows:

var z: if (y != null) y.length else

//It is explicitly checked whether y is null or not, then the operation is performed later.

Example: 

fun main() {
    var y: String? = "Coding Ninjas." // Initialization of a variable that allows the string to hold null values
    y = null // We do not encounter an error in this case. Nullable values are allowed.
    if (y != null) {
        println("String of length ${y.length}")
    } else {
        println("Null string")
    }
    // It is explicitly checked whether y is null or not, then the operation is performed later.

}

Output:

Null String

As mentioned above, as a method to implement null safety in Kotlin, we can explicitly check whether the variable is null as done with variable y. 

Filtering null values 

Null values can be filtered using the filterNotNull() function in Kotlin. It returns all the list values except the null value, and hence, the problem of eliminating the null values is implicitly solved. 

fun main() {
    val objecList: List<Int?> = listOf(1, 2, 3, null)
    // Defining a list with different  values in Kotlin
    val intList: List<Int> =objecList.filterNotNull() // filterNotNull()  function returns all the values of list except the null values
    print(intList.size); // Printing size of list which will br three after removing the null variable
}

Output:

3

Advance Null Safety 

Kotlin implements advance null safety by defining various advance operators like the safe call operator, Elvis operator, and Non-Null Insertion operator. 

Let us discuss these operators in Kotlin one by one.

  1. Safe Calls Operator
  2. Elvis Operator
  3. Non-Null Insertion Operator

Safe Calls Operator

We can access a property on a nullable variable by using the safe call operator. We represent the safe call operator as (?.).

The example for this is as follows:

fun main() {
    val x = "Hey Ninja."
    val y: String? = null
    println(y?.length)
    println(x.length)
}

Output:

null
10

The safe call operator returns the value of the length of the string x and y if the string isn’t null. Otherwise, null is given as an output.

Elvis Operator

Elvis operator works as an if-else operator only. We use the Elvis operator when you want to ask the compiler to use the variable's value if it is not null; else, we assign it a not null value.

Syntax example: val x: Int=x.legth?:-1

Let us take into reference the below code:

fun main() {
    val x = "Hey Ninja"
    val y: String? = null
    val l: Int = x.length ?: -1
    print(l)
}

Output:

9

The Not Null Assertion Operator

This operator gives NonNullException in the program. The not null assertion operator (!!) converts any value to a not null type. We encounter the NonNullException only when the variable holds a null value.

Syntax:

Val l= x!!.length

FAQs

  1. Why do we require Null Safety?
    Null Safety is a new productivity feature that allows users to avoid the program's null exceptions, which are not easy to find in a program.
     
  2. What is the difference between Kotlin and Java when there is a NullPinter Exception?
    Kotlin tends to give compiler errors, whereas Java will show NullPointException while runtime.
     
  3. What is the use of “?.” operator in Kotlin?
    It is a safe call operator to ensure null references. It performs any operation only when the reference has a non-null value.

Key Takeaways

Cheers if you reached here!!

The purpose of this article was to introduce you to Kotlin’s Null Safety, the problem of the NonNullException faced during runtime, various operators and methods such as declaring nullable and non-nullable values to tackle this problem.

If you want to learn more about decision statements in Kotlin, you can jump to this article which covers them in great detail.

However, learning never stops, and there is more to learn. So head over to our Android Development Course on the Coding Ninjas Website to dive deep into Android Development and build future applications. Till then, Happy Learning!

Live masterclass