Language Elements

Data Types

Kotlin Classes

Kotlin Operators

Kotlin Constructors

Kotlin Null Safety

Extension Functions

Lambda Functions

Object Oriented Kotlin

Data Classes

Coroutines

Kotlin Collections

Kotlin Data Structures

Kotlin Algorithms

Delegation

Lateinit and Lazy Initialization

Kotlin Scope Functions

Kotlin Key Words

Kotlin Example Codes

Kotlin Interview Questions

In Kotlin, a core principle is null safety, a feature designed to prevent the infamous NullPointerException (NPE), prevalent in Java and other languages, frequently causing frustrating bugs and application crashes.

To achieve this robust null safety, Kotlin's type system makes a crucial distinction:

Kotlin Non-nullable Types

In Kotlin, variables and function return types are non-nullable by default. This means that unless explicitly indicated otherwise, the compiler guarantees they will not be `null`.

Here variable declaraytion for `String` is non-nullable.

val nonNullableString: String = "This cannot be null" // Non-nullable String
            

To define a function with a **non-nullable** return type, declare the return type without the `?`. This function is guaranteed to return a non-null value of the specified type.

fun nonNullableMethod(): String {
    // Function logic that always returns a non-null String
    return "A non-null result"
}
            

Kotlin Nullable Types

To allow a variable or return type to accept `null` values, explicitly declare it as a nullable type by adding a question mark (?) to the end of the type declaration.

Here varibale decalrtion `String?` is nullable.

val nullableString: String? = null // Nullable String

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 handling in Kotlin

Kotlin provides powerful built-in tools to handle nullable variables safely and avoid runtime exceptions. Here are the main approaches:

Important:


Copyright © by Zafar Yasin. All rights reserved.