Null safety in kotlin
Author:
Views:
Category:
Null safety
Null Safety in Kotlin

In an effort to rid the world of NullPointerException, variable types in Kotlin don't allow the assignment of null. If you need a variable that can be null, declare it nullable by adding ? at the end of its type.

var neverNull: String = "This can't be null"

nullable = null

Here, declares a non-null String variable neverNull. In this case if try to assign null to non-nullable variable like nullable = null a compilation error will produce.


var nullable: String? = "You can keep a null here"      

nullable = null  

Here, declares a nullable String variable nullable. Sets the null value to the nullable variable. This is OK. No compilation error will produce.


var inferredNonNull = "The compiler assumes non-null"   

inferredNonNull = null

When inferring types(inferredNonNull variable), the compiler assumes non-null for variables that are initialized with a value. When trying to assign null to a variable with inferred type, a compilation error is produced.

PANEL SUBTITLE

TEXT