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.
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.
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:
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.
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.
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:
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.
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.
The above expression is equivalent to the below expression.
Now let’s have a look at an example.
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).
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.
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.
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!
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.