Explain what null safety is in Kotlin.
sobes.tech AI
Answer from AI
Null safety is a feature of the Kotlin language that prevents errors related to null references. It is achieved by creating two types of references: nullable (allowing null) and non-nullable (not allowing null).
Non-nullable types are declared as usual:
var nonNullableString: String = "Hello" // Cannot be null
Nullable types are declared using the ? symbol after the type name:
var nullableString: String? = "Hello" // Can be null
nullableString = null
Kotlin requires explicit handling of nullable types, preventing direct access to their members without a prior null check. The following mechanisms are provided:
-
Safe call operator (
?.): Calls a method or accesses a property only if the object is notnull. Otherwise, it returnsnull.val length = nullableString?.length // length will be Int? or null -
Elvis operator (
?:): Provides a default value if the expression on the left of the operator isnull.val nonNullLength = nullableString?.length ?: 0 // nonNullLength will be Int, 0 if nullableString is null -
Not-null assertion operator (
!!): Converts a nullable type to a non-nullable. If the value isnull, aNullPointerExceptionis thrown. Used when the developer is sure that the value is notnull.val sureLength = nullableString!!.length // Will throw NullPointerException if nullableString is null -
if-checks: Traditional null check using
if. The compiler smart casts nullable types to non-nullable inside theifblock if the null check passes.if (nullableString != null) { val length = nullableString.length // Here nullableString is considered as String }
These mechanisms allow explicit management of situations where a variable can be null, significantly reducing the likelihood of NullPointerException during program execution.