Using External Annotations

If you are using a Java library that is not annotated with @NotNull, Kotlin will complain about null-checks in many situations. To fix this, you can annotate the library without touching its code by using external annotations.

Simple case

We will use as an example, although annotations for this class (as well as many others, and eventually, all of the JDK) come with Kotlin out of the box.

Kotlin thinks that the getName() method may return null, and thus warns you. But you have read the Javadoc, and, maybe the source, and are sure that it never returns null. So you navigate to its declaration (attaching source is not required), and press Alt+Enter on it:

By selecting “Annotate as @NotNull” you let Kotlin and other tools know that getName() behaves well, and never lets you down. The error in you Kotlin code will go away.

More Difficult Case

Unlike getName(), another method in, listFiles(), may return null (when called on a non-existent file or not a directory). But when it returns something, it is an array that contains no nulls. Kotlin doesn’t know about it, and complains:

Until Java 8 comes out, we can not annotate types, so what we need is to alter the whole signature of the method. Again, navigate to its declaration, and press Alt+Enter:

When you choose “Specify Custom Kotlin Signature”, a balloon appears showing you the default signature. Just delete the question mark that bothers you:

Now the compiler knows everything: