Kotlin, known for its emphasis on null safety, introduces nullable types as a powerful feature to prevent null pointer exceptions. This concept is fundamental to writing robust and reliable Kotlin code.
In Kotlin, all types are non-nullable by default. Nullable types are explicitly declared using a question mark (?
) after the type name. This allows variables to hold null values, providing a clear distinction between nullable and non-nullable types.
To declare a nullable type, simply add a question mark after the type name:
var nullableString: String? = "Hello"
nullableString = null // This is allowed
var nonNullableString: String = "World"
// nonNullableString = null // This would cause a compilation error
Kotlin provides several ways to work safely with nullable types:
The safe call operator allows you to call methods or access properties on nullable types without risking a null pointer exception:
val length = nullableString?.length // Returns null if nullableString is null
The Elvis Operator provides a default value when a nullable expression is null:
val length = nullableString?.length ?: 0 // Returns 0 if nullableString is null
The not-null assertion operator converts a nullable type to a non-null type, throwing an exception if the value is null. Use this operator with caution:
val length = nullableString!!.length // Throws NullPointerException if nullableString is null
Kotlin's Smart Casts feature automatically casts nullable types to non-nullable within null-checked contexts:
if (nullableString != null) {
// nullableString is automatically cast to String (non-nullable) in this scope
println(nullableString.length)
}
Nullable types in Kotlin are a cornerstone of its null safety system. By understanding and properly utilizing nullable types, you can write more robust code, significantly reducing the risk of null pointer exceptions. This feature, combined with Kotlin's other null safety mechanisms, contributes to creating more reliable and maintainable applications.