Learn Kotlin · 5/18

Null Safety: Fixing the Billion Dollar Mistake

6 min read

Null Safety: Fixing the Billion Dollar Mistake 🛡️

Welcome to the world of Kotlin, where we tackle one of programming's most infamous problems head-on! Before we dive into the nitty-gritty, let's talk about the "Billion Dollar Mistake." In 1965, a computer scientist named Tony Hoare introduced the null reference. He later called it his "billion-dollar mistake" because of the countless errors, system crashes, and vulnerabilities it has caused over the decades.

The Problem: In many programming languages, if you try to use a variable that holds a null value (meaning it has no value), your program will crash with a NullPointerException (NPE). This is like trying to read a book with no pages – it just doesn't work!

Kotlin's Solution: Kotlin's type system is designed to eliminate the NullPointerException from our code. It does this by forcing us to explicitly deal with the possibility of null values at compile time, before the code even runs. This makes our code safer, more robust, and easier to read.


1. Nullable vs Non-Nullable Types: The '?' Modifier ❓

In Kotlin, we have to be very clear about whether a variable can hold a null value or not. This is the foundation of Kotlin's null safety.

Definition:

  • Non-Nullable Types: By default, all variables in Kotlin are non-nullable. This means they cannot hold a null value. If you try to assign null to a non-nullable variable, your code won't even compile.
  • Nullable Types: To allow a variable to hold null, you must explicitly mark its type with a question mark (?).

How it Solves the Problem: This distinction forces you to think about nullability from the very beginning. The compiler will then enforce these rules, preventing you from accidentally trying to use a null value where it's not expected.

Examples:

kotlin
// A non-nullable String. It can only hold a String value.
var name: String = "Alice"
// name = null // This will cause a compile-time error! ❌

// A nullable String. It can hold a String value or null.
var middleName: String? = "B"
middleName = null // This is perfectly fine. ✅

Under the Hood: At runtime, both nullable and non-nullable types are treated the same. The magic happens during compilation, where Kotlin's compiler checks for potential null issues. This means there's almost no performance overhead for this added safety.


2. Safe Calls ('?.') and the Elvis Operator ('?:') 🕶️

Now that we have variables that can be null, how do we safely use them without causing a crash? Kotlin provides some elegant tools for this.

Safe Calls (?.)

Definition: The safe call operator (?.) allows you to access properties or call methods on a nullable variable. If the variable is not null, the operation is performed. If the variable is null, the entire expression returns null, and your program continues without a crash.

How it Solves the Problem: It provides a concise and safe way to chain operations on potentially null objects, avoiding a NullPointerException.

Examples:

kotlin
var name: String? = "Bob"
var length = name?.length // If name is not null, length will be 3.
println(length) // Output: 3

name = null
length = name?.length // If name is null, length will be null.
println(length) // Output: null

The Elvis Operator (?:)

Definition: The Elvis operator (?:) is used with the safe call operator to provide a default value if the expression on the left-hand side is null. If the expression is not null, its value is returned.

Fun Fact: It's called the "Elvis operator" because when you look at it sideways (?:), it resembles an emoticon of Elvis Presley with his signature pompadour hairstyle! 🕺

How it Solves the Problem: It allows you to provide a fallback value in a very readable way, ensuring you always have a non-null value to work with.

Examples:

kotlin
var name: String? = null
val nameLength = name?.length ?: 0 // If name is null, use 0 as the length.
println(nameLength) // Output: 0

var city: String? = "New York"
val currentCity = city ?: "Unknown" // If city is not null, use its value.
println(currentCity) // Output: New York

You can even use throw on the right side of the Elvis operator to handle cases where a value is unexpectedly null.

kotlin
fun getUserName(): String {
    val name: String? = null // Let's pretend this comes from an API
    return name ?: throw IllegalArgumentException("Name cannot be null")
}

3. The Not-Null Assertion ('!!'): When to Use and Avoid 💥

Sometimes, you might be absolutely certain that a nullable variable is not null in a particular part of your code. For these situations, Kotlin provides the not-null assertion operator (!!).

Definition: The not-null assertion operator (!!) converts any value to a non-nullable type. If the value is not null, it will be returned as a non-nullable type. If the value is null, it will throw a NullPointerException.

How it Solves the Problem: It's a way to tell the compiler, "I know what I'm doing, this value will never be null here." This can be useful when you have knowledge about the code that the compiler doesn't.

When to Use (with caution!):

  • When you are 100% sure that a variable will not be null.
  • When interacting with Java libraries where a method might return a nullable type, but the library's documentation guarantees it won't be null in your specific use case.

When to Avoid:

  • In most of your Kotlin code. It's often a sign that your code could be structured more safely using safe calls or the Elvis operator. Overusing !! defeats the purpose of Kotlin's null safety.

Examples:

kotlin
var name: String? = "Charlie"
val length = name!!.length // This is safe because name is not null.
println(length) // Output: 7

name = null
// val length2 = name!!.length // This will crash your program with a NullPointerException! 💣

Industry Practice: In professional development, the use of !! is often discouraged. It's generally better to write code that safely handles nullability rather than asserting that something won't be null. Think of it as a last resort.


4. Safe Casting: The 'as?' Operator 🎭

Type casting is the process of converting a variable from one data type to another. Sometimes, this can fail and cause a ClassCastException. Kotlin provides a safe way to handle this.

Definition: The safe cast operator (as?) attempts to cast an object to a specified type. If the cast is successful, it returns the object of the new type. If the cast is not possible, it returns null instead of throwing an exception.

How it Solves the Problem: It prevents your application from crashing due to an invalid type cast by providing a safe way to attempt the cast and handle the failure gracefully.

Examples:

kotlin
val someValue: Any = "I am a String"
val myString: String? = someValue as? String // Successful cast
println(myString) // Output: I am a String

val anotherValue: Any = 123
val anotherString: String? = anotherValue as? String // Failed cast
println(anotherString) // Output: null

You can combine as? with the Elvis operator for even cleaner code:

kotlin
val yetAnotherValue: Any = 456
val yetAnotherString: String = yetAnotherValue as? String ?: "Not a String"
println(yetAnotherString) // Output: Not a String

By mastering these null safety features, you can write more reliable and expressive Kotlin code, leaving the fear of the "Billion Dollar Mistake" behind!

Additional Resources 📚

Challenge

Your task is to implement the processUserProfile function in Kotlin. This function accepts a Map<String, Any?> which represents a user's profile data. The map can contain keys like "name", "age", "email", and "subscriptionLevel", but any of these keys might be missing, or their values could be null or of an incorrect type.

You must process this data and return a formatted summary string. The use of the not-null assertion operator (!!) is strictly forbidden.

Requirements:

  1. Extract the user's name:

    • The name is associated with the "name" key and should be a String.
    • If the name is null or a blank string (contains only whitespace), use the default value "Guest".
  2. Extract the user's age:

    • The age is associated with the "age" key and should be an Int.
    • If the value is null or not an Int, use the default value 0.
  3. Extract the subscription level:

    • The subscription level is associated with the "subscriptionLevel" key and should be a String.
    • If the value is null or missing, use the default value "Basic".
    • The final subscription level string must be in UPPERCASE.
  4. Extract the user's email:

    • The email is associated with the "email" key and should be a String.
    • This field is optional.
  5. Construct the output string:

    • The base format is: "User: [Name], Age: [Age], Status: [Subscription Level]."
    • If a valid email address string is present, append it to the end like this: " Email: [Email]". If there is no email, this part should be omitted entirely.

Expected result

Your function should return a single formatted string based on the logic defined in the instructions.

For example:

  • Given mapOf("name" to "Alice", "age" to 30, "email" to "[email protected]", "subscriptionLevel" to "Premium"), your function should return:
    "User: Alice, Age: 30, Status: PREMIUM. Email: [email protected]"

  • Given mapOf("name" to null, "age" to "twenty-five", "email" to null), your function should return:
    "User: Guest, Age: 0, Status: BASIC."

  • Given mapOf("name" to " ", "age" to 25), your function should return:
    "User: Guest, Age: 25, Status: BASIC."

  • Given an empty map mapOf<String, Any?>(), your function should return:
    "User: Guest, Age: 0, Status: BASIC."

kotlin

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.