Say Bye to NullPointerException in Kotlin
As an Android developer, one of the main problems that you must address is facing with NullPointerException(NPE) in developing your codes with Java. Even though Java has some best practices to deal with, NPE has been remained as one of the most problematic issues for all developers, and statistics from the all over the world have been proved this claim as well. Fortunately, Kotlin as a modern and advanced language has focused on NullPointerException very well, and has some successful plans to solve it. This essay aims to discuss some best practices in Kotlin for NullPointerException.
Some cases that are used Null value in Java programming:
- It is mostly used to mention that no value is assigned to a reference variable.
- One application of null is in implementing some data structures such as linked list and tree.
- Using Null Object pattern in our projects.
- Singleton pattern: the Singleton pattern confirms that just only one instance of a class is created. Furthermore, it points to provide a global point of access to the object.
What is NullPointerException?
In fact, NullPointerException is a RuntimeException. In short, NullPointerException is thrown when a program attempts to use an object reference, which has the null value. For example:
public class SampleClass{ public static void main(String[] args){ String sampleString= null; System.out.println(sampleString.toString()); //Here! }
}
NullPointerException usually occurs in some common situations in Android programming with Java as follows:
- Accessing or modifying the field of null object
- Invoking methods on an object, which is not initialized
- Parameters passed in a method are null
- Throwing null with a Throw-able value
- Calling toString() method on object, which is null
- Comparing object properties block without checking null equality
- Taking the length of null as if it were an array
- Using synchronized on an object, which is null
- Chained statements like multiple method calls in a single statement
- Accessing or modifying the slots of null as if it were an array
How to avoid NullPointerException in Java
There are some best practices to avoid NullPointerException in Java that are mentioned some of them as below:
- String comparison with literals
- Avoid returning null from your methods
- Keep checking on arguments of methods
- Use String.valueOf() Rather than toString()
- Using primitives data types as much as possible
- Avoid chained method calls
- Using Ternary Operator
Kotlin Null Safety
Basically, Kotlin null safety has been proposed to eliminate NullPointerException form the code. NullPointerException can just only possible on following situations:
- Throw NullPointerException() as a forceful call
- Using external java code as Kotlin, which means Java interoperability.
- An uninitialized of this operator that is available in a constructor passed and used another place.
- Use of the !! operator
- A superclass constructor calls an open member.
How Kotlin avoids NullPointerException
- Kotlin Nullable Types and Non-Nullable Types
Actually, Kotlin differentiates between references that can hold null (nullable reference) ones, which cannot hold null (non-null reference). In other words, types of String are not nullable generally. Therefore, to create a string that holds null value, we have to explicitly define it by putting ? after String. For instance, in these two examples you can be able to observe this difference:
var sampleString : String? = "Test"
sampleString = null // There is no problem in executing because we declared this variable as a nullable.
print(sampleString) // The output of this code is printing the null.fun main(args: Array<String>){
var sampleTest: String = "Sample"
sampleTest = null //Compile Time Error!}
Important note:
Remember once you indicates a variable using a question mark in Kotlin, it will become a special type of variable, which only can be accessed by compile-time check.
2. Smart Cast
In order to use nullable types, Kotlin has an option that is called Smart Cast. In other words, Smart Cast is a feature in which Kotlin compiler traces situations inside if expression. So, if the compiler finds a variable, which is non-null of type then the compiler will allow you to access this variable safely.
For instance:
fun main(args: Array<String>){val sampleObject: Any = "Sample Test!"
if (sampleObject is String){
println("String length is ${sampleObject.length}")
} else {
println("String is null")
}
}
In other words, the Kotlin compiler converts the variable to a particular class reference automatically once it is passed through any conditional operator.
3. Kotlin Safe cast operator: as?
In some cases, it is not possible to cast types; therefore, it throws an exception, which is called unsafe cast. For instance, A nullable string (String?) cannot be cast to non-nullabe string (String). So, it throws an exception. To address this problem safely, Kotlin provides a safe cast operator as? to cast safely to another type. It means, if casting is not possible, it returns a null rather than throwing an ClassCastException.
For example:
fun main(args: Array<String>{ val sampleObject: Any? = "Sample Test"
val sampleString: String? = sampleObject as? String
println(sampleString) //The output is Sample Test! OK!}
4. Elvis operator
As a matter of fact, Kotlin indicates an advance operator, which is called Elvis operator(?:) that return the non-null value or default value even the conditional expression is null. Besides, it checks the null safety of values.
For instance:
fun main(args: Array<String>){
var firstSampleString: String? = null var secondSampleString: String? = "Second Sample Text" var firstVariable: Int = firstSampleString ?.length ?: -1 var secondVariable: Int = secondSampleString?.length ?: -1 println(“The length of firstSampleString is ${firstVariable}")
//Output: The length of firstSampleString is -1 println(“The length of secondSampleString is ${secondVariable}")
//Output: The length of secondSampleString is 18}
In conclusion
Although Java has some plans to solve the NullPointerException, particularly for Android developers, the problem has not solved yet properly. Thus, Kotlin as an advanced and modern language aims to face this issue with some successful strategies and best-practices.