Kotlin Tutoial

Basics

Control Flow

Array & String

Functions

Collections

OOPs Concept

Exception Handling

Null Safety

Regex & Ranges

Java Interoperability

Miscellaneous

Android

Kotlin Null Safety

Kotlin was designed to eliminate the null reference errors that are common in many languages, including Java. Null safety is one of Kotlin's most distinctive features. Let's dive into this topic:

1. Nullable Types:

In Kotlin, by default, variables cannot hold a null value. To declare a variable as nullable, you use ? after the type:

var name: String = "Alice"
// name = null // This will cause a compile-time error

var nullableName: String? = null // This is allowed

2. Safe Call Operator (?.):

You can use the safe call operator to safely access a property or method on a nullable variable. If the variable is null, the operation returns null.

val length: Int? = nullableName?.length

3. Elvis Operator (?:):

The Elvis operator allows you to provide a default value if a nullable expression resolves to null.

val len = nullableName?.length ?: 0

4. Not-null Assertion Operator (!!):

If you are certain that a nullable expression is non-null, you can use the !! operator. However, if the expression is null, it'll throw a NullPointerException.

val lenAgain: Int = nullableName!!.length // Throws NullPointerException if nullableName is null

5. Safe Casting (as?):

Kotlin provides a safe cast operator (as?), which tries to cast a value to a specified type and returns null if the cast is unsuccessful.

val anyValue: Any = 123
val stringValue: String? = anyValue as? String // This will be null, not a ClassCastException

6. Checking for null in Conditions:

You can check for null values using the == and != operators.

if (nullableName != null) {
    println(nullableName.length)
}

7. let with Safe Calls:

Using ?.let is a common pattern to perform an operation on a non-null value of a nullable variable:

nullableName?.let { 
    println("Name is $it and its length is ${it.length}")
}

8. lateinit:

If you have a non-null property that is not initialized in the constructor but you promise to initialize it before using, you can use the lateinit modifier. However, accessing it before initialization will throw an exception.

class Sample {
    lateinit var name: String

    fun initName() {
        name = "Kotlin"
    }
}

9. null in Collections:

Kotlin differentiates between a list that can have null elements and a list that cannot.

val listWithNulls: List<String?> = listOf("Kotlin", null, "Java")
val listWithoutNulls: List<String> = listWithNulls.filterNotNull()

Summary:

Kotlin's null safety features are designed to eliminate the risk of NullPointerException in your code. By using Kotlin's type system effectively and understanding these features, you can write more robust and error-resistant code.

  1. Nullable types in Kotlin:

    • Declare a variable as nullable by appending ? to its type.
    var nullableString: String? = "Hello, Kotlin!"
    
  2. Safe calls in Kotlin:

    • Use safe calls (?.) to access properties or call methods on nullable objects.
    val length: Int? = nullableString?.length
    
  3. Elvis operator in Kotlin null safety:

    • Use the Elvis operator (?:) to provide a default value if the expression is null.
    val lengthOrDefault: Int = nullableString?.length ?: 0
    
  4. !! operator and non-null assertions in Kotlin:

    • The !! operator asserts that an expression is non-null, use with caution.
    val nonNullLength: Int = nullableString!!.length
    
  5. The use of ?. in Kotlin null safety:

    • The ?. operator is used for safe calls to avoid null pointer exceptions.
    val firstChar: Char? = nullableString?.get(0)
    
  6. Checking for null with if and when statements in Kotlin:

    • Use if or when to explicitly check for null.
    if (nullableString != null) {
        // Code when not null
    } else {
        // Code when null
    }
    
  7. Default values for nullable variables in Kotlin:

    • Provide default values for nullable variables when declaring them.
    var nullableInt: Int? = null
    val nonNullInt: Int = nullableInt ?: 0
    
  8. Smart casts and type checks in Kotlin null safety:

    • Kotlin's smart casts automatically cast types after null checks.
    if (nullableString is String) {
        val length: Int = nullableString.length // Automatically cast to String
    }
    
  9. Nullable collections in Kotlin:

    • Collections can hold nullable types.
    val nullableList: List<String?> = listOf("one", null, "three")
    
  10. Working with nullable types in Kotlin functions:

    • Specify nullable types in function parameters and return types.
    fun concatStrings(str1: String?, str2: String?): String? {
        return str1?.plus(str2)
    }
    
  11. Null safety and Java interoperability in Kotlin:

    • Kotlin's null safety works seamlessly with Java code.
    val javaObject: JavaClass? = JavaClass()
    val length: Int? = javaObject?.getString()?.length