Kotlin - Null Safety

Introduction

 
Here we are going to learn about Kotlin Null Safety. Those who are new to Kotlin and willing to learn, go through this article series starting here for the Introduction to Kotlin.
 
 

Kotlin Null Safety 

 
Kotlin null safety is used to eliminate the risk of null references in the code if the Kotlin compiler finds any null argument is passed without executing any other statements.
 

Null Pointer Exception causes

  • A forceful call to throw NullPointerException();
  • An uninitialized use of "this" operator available in a constructor passed and used.
  • Use of Java code as Kotlin is in Java interoperatability.

Kotlin Nullable Types and Non-Nullable Types

 
Kotlin types system differentiates between references which can hold a null reference. The String is not nullable. Explicitly define them by putting the String as: String?
 

Nullable Types

 
Nullable types are declared by ? behind the String.
 
Example
  1. fun main(args: Array < String > ) {  
  2.     var str: String ? = "Hello" // variable is declared as nullable    
  3.     str = null  
  4.     print(str)  
  5. }  
Output
 
null
 

Non Nullable Types

 
Non-nullable types are declared as String.
 
Example
  1. fun main(args: Array < String > ) {  
  2.     var str: String = "Hello"  
  3.     str = null // compile error    
  4.     print(str)  
  5. }  
Output
 
It will generate a compile-time error.
 

Smart cast

 
To use nullable types, we can use smart casts. Smart cast is a feature in Kotlin compiler tracks conditions. If compiler finds a not null of type then the compiler will allow accessing the variable.
 
Example
  1. fun main(args: Array < String > ) {  
  2.     var string: String ? = "Hello!"  
  3.     if (string != null) { // smart cast    
  4.         print(string.length) // It works now!    
  5.     }  
  6. }  
Output
 
6
 

Smart cast conditions

  • A val variable is always for local properties.
  • If a val property is private or internal, it is performed in the same module within which the property is declared.
  • If the local var variable is not modified between the check and the usage, it is not captured in a lambda.

Unsafe and Safe Cast Operator

 
Unsafe cast operator: as
 
The cast variable and it throws an exception, this is called unsafe cast. The unsafe cast is performed by the operator as A nullable string cannot be cast to a non-nullabe string.
 
Example
  1. fun main(args: Array < String > ) {  
  2.     val obj: String ? = "String unsafe cast"  
  3.     val str: String ? = obj as String ? // Works    
  4.         println(str)  
  5. }  
Output
 
String unsafe cast
 

Kotlin Safe cast operator: as?

 
Kotlin provides a safe cast operator as? for the safe cast to a type. It returns a null if the casting is not possible rather than throwing a ClassCastException exception.
 
It casts the value if possible or returns null instead of throwing an exception even when casting is not possible.
 
Example
  1. fun main(args: Array < String > ) {  
  2.     val location: Any = "Kotlin"  
  3.     val safeString: String ? = location as ? String  
  4.     val safeInt: Int ? = location as ? Int  
  5.     println(safeString)  
  6.     println(safeInt)  
  7. }  
Output
 
Kotlin
null
 

Elvis Operator (?:)

 
Elvis operator (?:) is used to return the conditional expression as null. It is used to check the null safety of values.
 
We can declare a variable to hold a null reference. When a variable contains null reference, before using it in the program we will check its nullability. If a variable is not null then use its property, otherwise use some other non-null value.
 
Example
  1. fun main(args: Array < String > ) {  
  2.     var str: String ? = null  
  3.     var str2: String ? = "May be declare nullable string"  
  4.     var len1: Int =  
  5.         if (str != null) str.length  
  6.     else -1  
  7.     var len2: Int =  
  8.         if (str2 != null) str2.length  
  9.     else -1  
  10.     println("Length of str is ${len1}")  
  11.     println("Length of str2 is ${len2}")  
  12. }  
Output
 
Length of str is -1
Length of str2 is 30
 

Conclusion

 
In this article, we learned about null safety in Kotlin. In the next part, we will learn about Ranges, Reflections, Annotations. 
 
Next in this series: Kotin - Annotations and Reflection 


Similar Articles