One of Kotlin's best features is Kotlin Null safety. If you're familiar with Java, you've probably come across NullPointerException, which the creators of Kotlin introduced to eliminate or deal with this NullPointerException safely. In this article on Kotlin null safety, we will learn about various Null safety topics in detail.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

What Is Null Safety in Kotlin?

Kotlin's type system aims to eradicate NullPointerException from the code. The program throws NullPointerExceptions at runtime, which might result in application failure or system crashes.

If you've ever written code in Java or another language with the concept of null references, you've probably run across a NullPointerException. The type system in Kotlin was created with the Null pointer Exception in mind. One of the most common challenges developers face for many programming languages, including Java, is the Null Pointer Exception. It happens when you try to access members that have a null reference.

Non-Nullable Types vs. Nullable Types

There are two types of references in Kotlin: those that can't hold null and those that can. Non-nullable references are the first, and their type must be of a non-nullable type.

Let us have a look at an example.

Kotlin_Null_Safety_1

The code above fails to compile because Kotlin does not allow non-nullable reference types to be null.

Kotlin also includes a specific Nullable type for each type that can be used to make a reference null. For example:

Kotlin_Null_Safety_2.

This will not create a compilation error. As you can see, by adding the “?” Character to the end of the type name, you are making the variable a nullable reference. This is how nullable types are used in Kotlin, written as String?

Causes of Null Pointer Exception

Null Pointer Exception can occur for various reasons or faults in our code.

  • When a null reference is used to call a member function.
  • External Java code causes code issues.
  • When the developer calls throw NullPointerException() explicitly.
  • Usage of the !! operator

Now moving on to the safe calls operator.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

Safe Calls

Null comparisons are straightforward, but the number of nested if-else expressions can be challenging. So there's a Safe call operator in Kotlin? This makes things easier by only doing an action when a specified reference contains a non-null value. It enables us to conduct both a null check and a method call with a single expression.

Kotlin_Null_Safety_3

In this example, the safe call operator ?. will call the toUpperCase() function only when the value is not null; otherwise, it will return null. The Safe calls are generally used in chains; We can use safe expressions while chaining references as below.

For instance, if a Patient(say "patient") is admitted to a hospital that may have SeniorDoctor as a senior doctor. So as to retrieve the name of the senior doctor in the hospital then, we will be writing the following code:

patient?.hospital?.seniorDoctor?.name

But if any property in the above code turns out to be null, then the code will return null.

Moving on to the next operator of Kotlin Null safety.

Elvis Operator

The Elvis operator ?: in Kotlin allows you to return a default value when the original nullable variable is null. In other words, the Elvis operator returns the left expression of ?: if it is not null, otherwise it returns the right expression. This means that the expression on the right-hand side of the Elvis operator ?: is evaluated only if the left-hand side is null.

For example:

Kotlin_Null_Safety_4.

The above expression is equivalent to the below expression.

Kotlin_Null_Safety_5.

Now let’s have a look at an example.

Kotlin_Null_Safety_6

As we know, the expression on the right side of the Elvis operator is evaluated only if the left side returns null. So as we can see, str1 is null, and the Elvis operator returns expression left to ?: if it is not null, otherwise it returns expression right to (?:). So while printing the length of str1, it will display -1, and on printing the length of str2, it will print 20(including space). 

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

Not Null Assertion Operator

The not-null assertion operator !! in Kotlin throws a Kotlin NullPointerException if the variable to which it is applied is null. This operator changes any reference to its non-nullable type and throws an exception if the reference has a null value.

Kotlin_Null_Safety_7

Here we have assigned null to the string str, and we are printing str as well as printing the size of the string str. On running the code, it will show the output as mentioned below.

Kotlin_Null_Safety_8

As we have used the not-null assertion operator, it throws the kotlin NullPointerException because the variable which is assigned to it is null.

Master front-end and back-end technologies and advanced aspects in our Post Graduate Program in Full Stack Web Development. Unleash your career as an expert full stack developer. Get in touch with us NOW!

Conclusion

In this tutorial on Kotlin Null safety, you understand various topics, including Non-nullable types and Nullable types, Causes of Null pointer exception. You learned about operators like Safe calls, Elvis operator, and Not null assertion operator with the help of examples. 

If you are looking to build a software development career, you can check the Post-Graduate Program in Full Stack Development by Simplilearn. It can be the ideal solution to help you build your career in the right direction.

Do you have any questions about this Kotlin Null safety tutorial? If you do, feel free to post them in the comments section below. Our team will review and answer your questions at the earliest.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 16 Dec, 2024

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 27 Nov, 2024

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 18 Dec, 2024

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449