This tutorial aims to provide an in-depth look into the null safety feature in Kotlin, a significant improvement from the Java programming language.
By the end of this tutorial, you will understand how to declare nullable and non-nullable types, how to handle null pointer exceptions, and best practices for using null safety in Kotlin.
In Kotlin, every variable must be declared either as nullable or non-nullable. A nullable variable can hold a null value, whereas a non-nullable variable cannot.
By default, variables are non-nullable in Kotlin. Here's an example:
var name: String = "Kotlin"
If you try to assign null to this variable, it will result in a compile-time error:
name = null // Compilation error
To declare a variable as nullable, append a question mark to the type:
var name: String? = "Kotlin"
Now, you can assign null to this variable:
name = null // No error
Kotlin provides several operators for safely dealing with nullable types:
?.
: It returns null if used on a null reference.!!
: Converts nullable type to a non-nullable type, and throws a NullPointerException if the nullable type holds a null value.?:
: Returns the left-hand expression if it's non-null; otherwise, it returns the right-hand expression.var name: String? = null
// Use safe call operator
println(name?.length) // It will print 'null' because name is null.
var name: String? = null
// Use non-null assertion operator
println(name!!.length) // It will throw NullPointerException because name is null.
var name: String? = null
// Use Elvis operator
println(name?.length ?: "Name is null") // It will print 'Name is null' because name is null.
We've learned that Kotlin provides a robust system for avoiding null pointer exceptions. By distinguishing nullable and non-nullable types, and providing helpful operators, Kotlin makes your code safer and more expressive.
Declare a nullable String variable and a non-nullable Int variable. Try assigning null to both of them and observe the results.
Experiment with the safe call operator, non-null assertion operator, and Elvis operator. Create different scenarios to understand their functionality.
var nullableString: String? = "Kotlin"
nullableString = null // No error
var nonNullableInt: Int = 10
nonNullableInt = null // Compilation error
2.
var name: String? = null
// Safe call operator
println(name?.length) // prints null
// Non-null assertion operator
// println(name!!.length) // Uncommenting this will throw NullPointerException
// Elvis operator
println(name?.length ?: "Name is null") // prints 'Name is null'
Continue exploring more about Kotlin's null safety features from the official Kotlin documentation.