In Kotlin, variables and method return types are non-nullable by default. They need to be explicitly indicated when nullable types.
val nullableString: String? = null // Nullable String
Use safe calls (?.), the Elvis operator (?:), or null checks to work with nullable variables safely.
Kotlin Nullable Types
To declare a method (function) as returning a nullable type in Kotlin, simply add ? to the type declaration of the return type. The method can return either a non-null value of the specified type or null.
fun nullableMethod(): ReturnType? { // Function logic that can return null or a non-null value // As example, return null return null }
Null-Safety
To handle null safety explicitly use safe calls (?.), the Elvis operator (?:), or null checks to work with nullable variables safely.val length: Int? = nullableString?.length // Safe call to access length property val result: String = nullableString ?: "Default Value" // Elvis operator
Not-null Assertion Operator
!! Indicates that a type or parameter is non-nullable, and you can call functions or access properties without null checks, but risk runtime exceptions if null values are encountered.
Use !! when it is certain that a value is not null, as incorrect use of !! can lead to crashes.
Note: Use !! with caution, as it bypasses Kotlin's null safety checks, and if you use it incorrectly with a value that is actually null, it can lead to runtime exceptions.
It's generally recommended to handle nullability using safe calls (?.) or null checks (if (x != null)) to ensure code reliability and safety.