Rolling out @Nullable

Lots of us have strong opinions on null. I don’t think it’s evil, or that using null is sloppy. I just want to be deliberate: wherever a parameter or return value can be null, the interpretation of that should be explicit.

/** 
* Consumes the next line of text and returns it.
* Returns null if there are no more lines.
*/
String readUtf8Line() throws IOException;

Kotlin’s great because it requires us to be explicit when we use null. Declaring the same method in Kotlin puts null into the type system.

/**
* Consumes the next line of text and returns it.
* Returns null if there are no more lines.
*/
fun readUtf8Line(): String?

But what happens when we want to call Java APIs from Kotlin? We need an annotation to signal that our return value can be null. But — frustratingly— there isn’t a @Nullable annotation built-in to Java. Instead, we need to pick a third-party library to supply it:

  • Android’s Nullable is a good choice for Android-only projects, but we’re writing libraries that need to work on both Android and Java.
  • The Checker Framework’s Nullable supports Java 8’s type annotations, which allows it to express concepts like ArrayList<@Nullable String> .
  • JSR 305’s Nullable has a standard-looking javax.annotation package name. This is the one used by Guava, the gold standard in open source Java.

We’re following Guava’s lead and will adopt javax.annotation.Nullable in our open source projects. Java users benefit by getting additional support from their IDEs and static analysis tools. Kotlin users get even more: compiler-enforced null safety. If your current Kotlin code is not null-safe you’ll need to fix it when you integrate these updates.

The dependency is compile-time only, so your build scripts won’t change and your binaries won’t get any bigger.

Today we’re releasing Okio 1.13 which adds @Nullable to help you to avoid problems with null. Over the next few days we’ll follow up with releases of our other open source libraries. Enjoy!

This post is part of Square’s “Square Open Source ♥s Kotlin” series.