Null handling is a concept that can sometimes confuse both new and experienced developers. In Kotlin, nullability is treated with special care, and its features make handling nulls safe and concise. But have you ever wondered what happens when you add null + null in Kotlin? In this quick dive, we’ll explore what occurs and demystify nullability in Kotlin along the way.

Understanding Nullability in Kotlin

One of the reasons why Kotlin is such a beloved language among Android developers is its strong type system and null safety features. Unlike Java, where any reference type can be null, in Kotlin, you need to explicitly specify if a variable can hold a null value by appending a question mark ? to its type.


// A nullable String type
val name: String? = null

By default, all variables in Kotlin are non-nullable. This means if you try to assign a null to a non-nullable variable, you will get a compilation error.

The Null + Null Scenario

So, what happens if you try to add two null values together in Kotlin? Let’s look at the code:


// Trying to add null values
val result = null + null

This code will actually give a compilation error. The Kotlin compiler will not allow this operation, as it doesn’t make sense to perform arithmetic operations on null values. Here’s why:

  • Null Safety: Kotlin’s type system is designed to eliminate the danger of NullPointerExceptions (NPEs). Arithmetic operations require valid operands, and since null is not a number or valid operand, this type of operation is disallowed.
  • Operator Overloading: The + operator is overloaded in Kotlin to perform various operations based on the types of its operands (e.g., adding two numbers, concatenating two strings). Since null is not an applicable type for these operations, it doesn’t know how to handle null + null.

How to Work with Nulls in Kotlin

Kotlin provides several ways to safely handle nullable types. Let’s explore some of them:

1. Safe Call Operator ?.

The safe call operator allows you to safely access properties and methods on a nullable type without causing an NPE.


val name: String? = null
val length = name?.length // Returns null instead of throwing an exception

If name is null, length will also be null instead of throwing an exception.

2. Elvis Operator ?:

The Elvis operator provides a default value if a nullable expression evaluates to null. (Java: A ? A : B)


val name: String? = null
val displayName = name ?: "Unknown"

In this case, displayName will be “Unknown” because name is null.

3. Null Safety with let

You can also use the let function to execute code only when a variable is not null.


val name: String? = "Kotlin"
name?.let {
    println("The name length is ${it.length}")
}

Here, the code inside let will only run if name is not null.

Nullable Types in Arithmetic Operations

While adding null + null directly will cause a compilation error, you can perform arithmetic operations on nullable types by checking for nullability:


val a: Int? = null
val b: Int? = 5
val sum = (a ?: 0) + (b ?: 0) // Sum will be 5

In the above code, the Elvis operator provides default values for a and b in case they are null.

Understanding Null Safety in Kotlin

Kotlin’s null safety is designed to make your code more robust by preventing NullPointerExceptions, a common source of runtime crashes in Java. By requiring you to explicitly handle nullable types, Kotlin makes it easier to write safe and predictable code.

If you want to explore more about Kotlin’s type system and key features, check out this article: Understanding Kotlin Flow and Its Key Features.

Conclusion

Adding null + null directly in Kotlin will result in a compilation error. This behavior is intentional, as Kotlin is designed to prevent unsafe operations involving nulls. By using the safe call operator, Elvis operator, and let function, you can safely handle nullable types and avoid potential pitfalls. Embracing null safety in Kotlin not only makes your code more reliable but also makes you more confident when handling nulls.

Remember, Kotlin’s approach to nullability is not something to be scared of—it’s a powerful tool that ensures your applications are more robust and error-free.

Source

Did you like this article?
You can subscribe to my newsletter below and get updates about my new articles.

Shares:
Leave a Reply

Your email address will not be published. Required fields are marked *