How to mark Java library as nullable

Posted by Java developer blog on July 12, 2019

Sometimes it is useful to mark a Java library as Nullable so you will be able to use it safely from Kotlin.

Let’s start with a simple example. The example consists of a kotlin project that depend on a java library.

The following picture shows a simple code example.

Our goal is to change Java types from Platform to Nullable.

Add jsr305 dependency to a java library pom file:

1
2
3
4
5
<dependency>
    <groupId>com.google.code.findbugs</groupId>
    <artifactId>jsr305</artifactId>
    <version>3.0.2</version>
</dependency>

Create a NullableApi annotation like the following below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.maks.foo;

import javax.annotation.Nullable;
import javax.annotation.meta.TypeQualifierDefault;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@TypeQualifierDefault({ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PACKAGE)
@Nullable
public @interface NullableApi {
}

Add a package-info.java file to the package (right click on a module in IDE) and mark the package with it. Look at the picture below

1
2
@NullableApi
package com.maks.foo;

In the end you should be able to see Nullable Java types in Kotlin code. It means that everything works.

If you don’t know how to enable Kotlin type hints then you could look at the following post.

You could get a code of the example here