Java 与 Kotlin 中的可空性

Nullability is the ability of a variable to hold a null value. When a variable contains null, an attempt to dereference the variable leads to a NullPointerException. There are many ways to write code in order to minimize the probability of receiving null pointer exceptions.

This guide covers differences between Java’s and Kotlin’s approaches to handling possibly nullable variables. It will help you migrate from Java to Kotlin and write your code in authentic Kotlin style.

The first part of this guide covers the most important difference – support for nullable types in Kotlin and how Kotlin processes types from Java code. The second part, starting from Checking the result of a function call, examines several specific cases to explain certain differences.

Learn more about null safety in Kotlin.

Support for nullable types

The most important difference between Kotlin’s and Java’s type systems is Kotlin’s explicit support for nullable types. It is a way to indicate which variables can possibly hold a null value. If a variable can be null, it’s not safe to call a method on the variable because this can cause a NullPointerException. Kotlin prohibits such calls at compile time and thereby prevents lots of possible exceptions. At runtime, objects of nullable types and objects of non-nullable types are treated the same: A nullable type isn’t a wrapper for a non-nullable type. All checks are performed at compile time. That means there’s almost no runtime overhead for working with nullable types in Kotlin.

We say “almost” because, even though intrinsic checks are generated, their overhead is minimal.

可空性 - 图1

In Java, if you don’t write null checks, methods may throw a NullPointerException:

  1. // Java
  2. int stringLength(String a) {
  3. return a.length();
  4. }
  5. void main() {
  6. stringLength(null); // Throws a `NullPointerException`
  7. }

This call will have the following output:

  1. java.lang.NullPointerException: Cannot invoke "String.length()" because "a" is null
  2. at test.java.Nullability.stringLength(Nullability.java:8)
  3. at test.java.Nullability.main(Nullability.java:12)
  4. at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
  5. at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)

In Kotlin, all regular types are non-nullable by default unless you explicitly mark them as nullable. If you don’t expect a to be null, declare the stringLength() function as follows:

  1. // Kotlin
  2. fun stringLength(a: String) = a.length

The parameter a has the String type, which in Kotlin means it must always contain a String instance and it cannot contain null. Nullable types in Kotlin are marked with a question mark ?, for example, String?. The situation with a NullPointerException at runtime is impossible if a is String because the compiler enforces the rule that all arguments of stringLength() not be null.

An attempt to pass a null value to the stringLength(a: String) function will result in a compile-time error, “Null can not be a value of a non-null type String”:

Passing null to a non-nullable function error

If you want to use this function with any arguments, including null, use a question mark after the argument type String? and check inside the function body to ensure that the value of the argument is not null:

  1. // Kotlin
  2. fun stringLength(a: String?): Int = if (a != null) a.length else 0

After the check is passed successfully, the compiler treats the variable as if it were of the non-nullable type String in the scope where the compiler performs the check.

If you don’t perform this check, the code will fail to compile with the following message: “Only safe (?.) or non-nullable asserted (!!.) calls are allowed on a nullable receiver of type String?”.

You can write the same shorter – use the safe-call operator ?. (If-not-null shorthand), which allows you to combine a null check and a method call into a single operation:

  1. // Kotlin
  2. fun stringLength(a: String?): Int = a?.length ?: 0

Platform types

In Java, you can use annotations showing whether a variable can or cannot be null. Such annotations aren’t part of the standard library, but you can add them separately. For example, you can use the JetBrains annotations @Nullable and @NotNull (from the org.jetbrains.annotations package) or annotations from Eclipse (org.eclipse.jdt.annotation). Kotlin can recognize such annotations when you’re calling Java code from Kotlin code and will treat types according to their annotations.

If your Java code doesn’t have these annotations, then Kotlin will treat Java types as platform types. But since Kotlin doesn’t have nullability information for such types, its compiler will allow all operations on them. You will need to decide whether to perform null checks, because:

  • Just as in Java, you’ll get a NullPointerException if you try to perform an operation on null.
  • The compiler won’t highlight any redundant null checks, which it normally does when you perform a null-safe operation on a value of a non-nullable type.

Learn more about calling Java from Kotlin in regard to null-safety and platform types.

Support for definitely non-nullable types

In Kotlin, if you want to override a Java method that contains @NotNull as an argument, you need Kotlin’s definitely non-nullable types.

For example, consider this load() method in Java:

  1. import org.jetbrains.annotations.*;
  2. public interface Game<T> {
  3. public T save(T x) {}
  4. @NotNull
  5. public T load(@NotNull T x) {}
  6. }

To override the load() method in Kotlin successfully, you need T1 to be declared as definitely non-nullable (T1 & Any):

  1. interface ArcadeGame<T1> : Game<T1> {
  2. override fun save(x: T1): T1
  3. // T1 is definitely non-nullable
  4. override fun load(x: T1 & Any): T1 & Any
  5. }

Learn more about generic types that are definitely non-nullable.

Checking the result of a function call

One of the most common situations where you need to check for null is when you obtain a result from a function call.

In the following example, there are two classes, Order and Customer. Order has a reference to an instance of Customer. The findOrder() function returns an instance of the Order class, or null if it can’t find the order. The objective is to process the customer instance of the retrieved order.

Here are the classes in Java:

  1. //Java
  2. record Order (Customer customer) {}
  3. record Customer (String name) {}

In Java, call the function and do an if-not-null check on the result to proceed with the dereferencing of the required property:

  1. // Java
  2. Order order = findOrder();
  3. if (order != null) {
  4. processCustomer(order.getCustomer());
  5. }

Converting the Java code above to Kotlin code directly results in the following:

  1. // Kotlin
  2. data class Order(val customer: Customer)
  3. data class Customer(val name: String)
  4. val order = findOrder()
  5. // Direct conversion
  6. if (order != null){
  7. processCustomer(order.customer)
  8. }

Use the safe-call operator ?. (If-not-null shorthand) in combination with any of the scope functions from the standard library. The let function is usually used for this:

  1. // Kotlin
  2. val order = findOrder()
  3. order?.let {
  4. processCustomer(it.customer)
  5. }

Here is a shorter version of the same:

  1. // Kotlin
  2. findOrder()?.customer?.let(::processCustomer)

Default values instead of null

Checking for null is often used in combination with setting the default value in case the null check is successful.

The Java code with a null check:

  1. // Java
  2. Order order = findOrder();
  3. if (order == null) {
  4. order = new Order(new Customer("Antonio"))
  5. }

To express the same in Kotlin, use the Elvis operator (If-not-null-else shorthand):

  1. // Kotlin
  2. val order = findOrder() ?: Order(Customer("Antonio"))

Functions returning a value or null

In Java, you need to be careful when working with list elements. You should always check whether an element exists at an index before you attempt to use the element:

  1. // Java
  2. var numbers = new ArrayList<Integer>();
  3. numbers.add(1);
  4. numbers.add(2);
  5. System.out.println(numbers.get(0));
  6. //numbers.get(5) // Exception!

The Kotlin standard library often provides functions whose names indicate whether they can possibly return a null value. This is especially common in the collections API:

  1. fun main() {
  2. //sampleStart
  3. // Kotlin
  4. // The same code as in Java:
  5. val numbers = listOf(1, 2)
  6. println(numbers[0]) // Can throw IndexOutOfBoundsException if the collection is empty
  7. //numbers.get(5) // Exception!
  8. // More abilities:
  9. println(numbers.firstOrNull())
  10. println(numbers.getOrNull(5)) // null
  11. //sampleEnd
  12. }

Aggregate operations

When you need to get the biggest element or null if there are no elements, in Java you would use the Stream API:

  1. // Java
  2. var numbers = new ArrayList<Integer>();
  3. var max = numbers.stream().max(Comparator.naturalOrder()).orElse(null);
  4. System.out.println("Max: " + max);

In Kotlin, use aggregate operations:

  1. // Kotlin
  2. val numbers = listOf<Int>()
  3. println("Max: ${numbers.maxOrNull()}")

Learn more about collections in Java and Kotlin.

Casting types safely

When you need to safely cast a type, in Java you would use the instanceof operator and then check how well it worked:

  1. // Java
  2. int getStringLength(Object y) {
  3. return y instanceof String x ? x.length() : -1;
  4. }
  5. void main() {
  6. System.out.println(getStringLength(1)); // Prints `-1`
  7. }

To avoid exceptions in Kotlin, use the safe cast operator as?, which returns null on failure:

  1. // Kotlin
  2. fun main() {
  3. println(getStringLength(1)) // Prints `-1`
  4. }
  5. fun getStringLength(y: Any): Int {
  6. val x: String? = y as? String // null
  7. return x?.length ?: -1 // Returns -1 because `x` is null
  8. }

In the Java example above, the function getStringLength() returns a result of the primitive type int. To make it return null, you can use the boxed type Integer. However, it’s more resource-efficient to make such functions return a negative value and then check the value – you would do the check anyway, but no additional boxing is performed this way.

可空性 - 图3

下一步做什么?

If you have a favorite idiom, feel free to share it with us by sending a pull request!