Dealing with NullPointerException
Kotlin offers many successful strategies to tackle NullPointerException in programming. The techniques used are listed as follows:
- Kotlin Nullable and Non-Nullable Types
- Smart Cast
- Kotlin safe cast operator
- 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.
- Safe Calls Operator
- Elvis Operator
- 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
-
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.
-
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.
-
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!