Sobes.tech
Junior — Middle

What does the Nullable data type mean in Kotlin and how to use it?

sobes.tech AI

Answer from AI

In Kotlin, the data type Nullable means that a variable can contain either a value of the specified type or null. To denote a nullable type, a question mark ? is used after the type, for example, String? — which is a string that can be null.

Using nullable types helps avoid NullPointerException errors, as the compiler forces explicit handling of null cases.

Example:

var name: String? = null

// Safe call method
val length = name?.length // returns the length of the string or null if name == null

// Elvis operator for default value
val lengthOrZero = name?.length ?: 0

// Null check
if (name != null) {
    println(name.length) // safe
}
What does the Nullable data type mean in Kotlin and… - sobes.tech