Kotlin Null SafetyKotlin null safety is a procedure to eliminate the risk of null reference from the code. Kotlin compiler throws NullPointerException immediately if it found any null argument is passed without executing any other statements. Kotlin's type system is aimed to eliminate NullPointerException form the code. NullPointerException can only possible on following causes:
Kotlin Nullable Types and Non-Nullable TypesKotlin types system differentiates between references which can hold null (nullable reference) and which cannot hold null (non null reference). Normally,types of String are not nullable. To make string which holds null value, we have to explicitly define them by putting a ? behind the String as: String? Nullable TypesNullable types are declared by putting a ? behind the String as: Kotlin example of nullable types Output: null Non Nullable TypesNon nullable types are normal strings which are declared as String types as: What happens when we assign null value to non nullable string? Output: It will generate a compile time error. Error:(3, 11) Kotlin: Null can not be a value of a non-null type String Checking for null in conditionsKotlin's If expression is used for checking condition and returns value. Output: str is : Hello str length is : 5 str is : null b length is : -1 Next TopicKotlin Smart Cast |