Kotlin Language Features Related to Null Handling
Any software engineer with a Java background would find the null handling features in the Kotlin language interesting. Let's summarize this topic with some examples.
Nullable types:
In Kotlin, types are non-nullable by default. If you want a variable to be able to hold a null value, you need to explicitly declare its type as nullable using the Type? syntax. For example, String? denotes a nullable string, while String represents a non-nullable string.
Safe calls (?.):
Kotlin introduces the safe call operator (?.) for handling nullable types. It allows you to safely invoke a method or access a property on a nullable object. If the object is null, the expression returns null instead of throwing a NullPointerException.
Example:
data class Person(val name: String, val age: Int, val address: String?)
fun main() {
// Create a person with a nullable address
val person1 = Person("John Doe", 25, "123 Main Street")
val person2 = Person("Jane Doe", 30, null)
// Safe call to access the nullable address property
val person1AddressLength = person1.address?.length
val person2AddressLength = person2.address?.length
// Print the results
println("Person 1 address length: $person1AddressLength") // Output: Person 1 address length: 14
println("Person 2 address length: $person2AddressLength") // Output: Person 2 address length: null
}
Elvis operator (?:):
The Elvis operator is used to provide a default value when a nullable expression is null. It is denoted by ?:. This can be useful for providing a default value or handling null cases gracefully.
Non-null assertion (!!):
The non-null assertion operator (!!) is used to assert that a nullable expression is non-null. However, if the expression is null, a NullPointerException will be thrown. It should be used cautiously, and it's generally better to rely on safe calls and proper null checks.
val length: Int = nullableString!!.length
Comments