Kotlin in Hindi Null Safety
Null Safety in Kotlin is to eliminate the risk of occurrence of NullPointerException in real time. If you are a Java developer, you might have definitely come across the atrocities of NullPointerException it creates during real time. NullPointerException is so popular as NPE (NullPointerException), since it costed billions of dollars to companies. Kotlinis so concerned about this, and made its type system in such a way that it eliminates the usage of NullPointerException, unless you want it explicitly. Thank you Kotlin.
Kotlin could never throw a NullPointerException unless you ask for it.
Of course there are ways you might give NullPointerException a chance to live one more Exception again. Let us see how could this happen :
- When you ask for a NullPointerException explicitly
- to throw a NullPointerException or
- use !! operator. This operator comes with a disclaimer for usage : You have been warned! And yet you chose to live with NullPointerException.
- From Outside Kotlin
- You may be aware that you can run external Java code in your application. And this external Java Code is not NullPointerException proof, unless you make it so.
- Data inconsistency
How Kotlin handles Null Safety ?
Following are some of the ways to handle Null Safety in Kotlin :
- Differentiate between nullable references and non-nullablereferences.
- User explicitly checks for a null in conditions
- Using a Safe Call Operator (?.)
- Elvis Operator (?:) : If reference to a val is not null, use the value, else use some default value that is not null
Differentiate between nullable and non-nullable references
Kotlin’s type system can differentiate between nullable references and non-nullable references. ? operator is used during variable declaration for the differentiation.
To make a variable hold a null value, follow the below example and observe the usage of ? in the program
Program:
fun main(args: Array<String>){
var a: String = "Hello !" // variable is declared as non-null by default
println("a is : $a")
// kotlin prevents you assign a null to a non-nullable variable
// a=null //assing null to a causes complilation error
var b: String? = "Hi !" // variable is declared as nullable
println("b is : $b")
b = null
println("b is : $b")
}
output: