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 java.io.File 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 java.io.File, 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:

4 Responses to Using External Annotations

  1. Zemian Deng says:

    Hi,

    So how do you do this “external-annotation” without the IDE?

  2. If the source to be annotated is part of the project, Idea wants to put the Kotlin signature in the source code as annotation.
    This forces me to include the annotation and requires a dependency to the annotations jar. However in my project, such a dependecy is not allowed.
    Can I tell Idea, to always put the annotation in the external XML file?

    • Evgeny Gerashchenko says:

      Unfortunately, IDEA doesn’t support external annotations for source files, only for libraries. Why isn’t it possible to add dependencies on annotations jar in your project?

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">