Language Elements

Data Types

Kotlin Nullable Types

Extension Functions

Lambda Functions

Object Oriented Kotlin

Data Classes

Collections

Kotlin Example Codes

Kotlin Interview Questions

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:

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.




Copyright © by Zafar Yasin. All rights reserved.