In Kotlin, variables and function return types are non-nullable by default. To allow null values, you must explicitly specify a nullable type by adding ?
to the type declaration.
val nullableString: String? = null // Nullable String
Kotlin provides built-in tools like safe calls (?.), the Elvis operator (?:), and null checks to handle nullable variables safely and avoid runtime exceptions.
Kotlin Nullable Types
To define a function with a nullable return type, add ?
to the type declaration. Such functions can return either a value of the specified type or null
.
fun nullableMethod(): String? { // Function logic that can return null or a non-null value return null }
Null-Safety
Kotlin provides several approaches to handle nullable values:
-
Safe Calls (?.): Use the
?.
operator to access properties or methods on a nullable variable without risking aNullPointerException
. If the variable isnull
, the operation returnsnull
. -
Elvis Operator (?:): Use the
?:
operator to provide a default value when a nullable expression evaluates tonull
. -
Explicit Null Checks: Check for
null
explicitly usingif
conditions for more control.
val length: Int? = nullableString?.length // Safe call to access the length property val result: String = nullableString ?: "Default Value" // Elvis operator to handle null
Not-null Assertion Operator
The !! operator is used to assert that a variable is non-nullable. It allows you to call methods or access properties directly without null checks. However, it will throw a KotlinNullPointerException
at runtime if the variable is null
.
val nonNullValue: Int = nullableString!!.length // Throws an exception if nullableString is null
Important: Use !!
with caution, as it bypasses Kotlin's null-safety features. It is generally better to use safe calls (?.
) or null checks to ensure code reliability.