Loading, please wait...

A to Z Full Forms and Acronyms

What is Null safety in Kotlin? | Kotlin Tutorial

Jan 31, 2022 #KotlinLanguage #Programming, 1315 Views
In this article, we will discuss the following pointers: What is Null Safety in kotlin? The difference between Nullable and Non-Nullable types. The cause through which NullPointerException occurs. What is the condition for checking null? How can we handle Null safety in kotlin?

What is Null safety in Kotlin? | Kotlin Tutorial

In this article, we will discuss the following pointers:

  • What is Null Safety in kotlin?
  • The difference between Nullable and Non-Nullable types.
  • The cause through which NullPointerException occurs.
  • What is the condition for checking null?
  • How can we handle Null safety in kotlin?

What is Null Safety in kotlin?

Null Safety is a process to eliminate the risk of occurrence of NullPointerException. It reduces the risk of null reference within the code. It throws NullPointerException immediately if it found any other null pointer without any other statement. 

Difference between Nullable and Non-Nullable

Nullable Type

The reference which can hold a null value is known as the nullable type. It is declared by using a ? in front of the string. 

Syntax:

var a:String? = “Hi”

a = null

Example:

fun main(args: Array<String>)

{

     var a:String? = “Hi”

     a = null

     print(a)

}

OUTPUT:

null

Non-Nullable

The reference which can not hold a null value is known as the non-nullable type. It is a normal string that is declared as a string type. 

Syntax:

val str1: String = “Hi” // It gives a compiler error messages

str1 = “Hi” // It gives a compiler error message because val can not be reassign

var a: String = “Hi” 

a = null // It gives the compile time error.

Example:

fun main(args: Array<String>)

{

     var a:String = “Hi”

     a = null

     print(a)

}

OUTPUT:

It gives the compile-time error

Cause of NullPointerException

  • When we explicitly call a NullPointerException throw. 
  • Using ! ! this operator also gives NullPointeException.
  • We know we are allowed to use the Java code in the program. It is not having the NullPointerException.
  • Due to Data inconsistency also NullPointerException occurs.

What is the condition of checking null? 

If the expression is used for checking the null condition and returns a value. 

fun main(args: Array<String>){  

var a: String? = "Hi" // variable is declared as nullable  

var l = if(a!=null) a.length else -1  

println("String is : $a")  

println("String length is : $l")  

 

a = null  

println("Stringtr is : $a")  

l = if(a!=null) a.length else -1  

println("a length is : $l")  

}

OUTPUT:

a is : Hi

a length is : 5

a is : null

a length is : -1

 

Handling the Null Safety in Kotlin

  • Users have to check explicitly for the null condition. 
  • Make use of the Safe Call operator(?.)
  • Use Elvis Operator(?:)
A to Z Full Forms and Acronyms

Related Article