How does Kotlin handle values that can be null, and what mechanisms does it provide for this?
sobes.tech AI
Answer from AI
Kotlin has a built-in null safety system that helps avoid the common NullPointerException error. By default, types in the language cannot contain null. To allow a variable to hold null, its type is declared with a ?.
Example:
var a: String = "Hello" // cannot be null
var b: String? = null // can be null
To work with nullable types, Kotlin provides several mechanisms:
-
Safe call (
?.) — allows calling a method or property if the object is not null, otherwise returns null.val length = b?.length // if b is not null, returns length, otherwise null -
Elvis operator (
?:) — returns the value on the left if it is not null, otherwise the value on the right.val length = b?.length ?: 0 // if b is null, length will be 0 -
Not-null assertion operator (
!!) — asserts that the value is not null, and if it is, throws an exception.val length = b!!.length // if b is null, an exception will be thrown -
Functions like
let,run,also, and others with safe calls for working with nullable objects.
Thus, Kotlin forces explicit handling of null, reducing the likelihood of runtime errors.