1.

Explain the concept of null safety in Kotlin.

Answer»

Kotlin's type system aims to eradicate null REFERENCES from the code. If a program throws NullPointerExceptions at runtime it might result in application failure or system crashes. If the Kotlin compiler finds a null REFERENCE it throws a NullPointerException.

The Kotlin type system distinguishes between references that can hold null (nullable references) and those that cannot (non-null references). Null cannot be stored in a String variable. We get a compiler error if we try to assign null to the variable. 

var a: String = "interview"a = null // results in compilation error

If we want the above string to be ABLE to hold null value as well, we can declare it of type nullable using the ‘?’ operator after the String keyword as follows :

var a: String? = "interview"a = null // no compilation error

Kotlin PROVIDES Safe Call (?.), Elvis (?:) and Not Null Assertion (!!) operators which define what needs to be done in case of a null encounter. This makes the code more reliable and less prone to errors. Thus, Kotlin ENFORCES null safety by having nullable, non-nullable type variables and the different operators to tackle null encounters.



Discussion

No Comment Found