Search code examples
annotationskotlinnon-nullable

Annotate Type Parameter in Java for Kotlin Compiler


In Java, I have the following method:

public Optional<Foo> getFoo() {
    // always return some non-null value
}

In Kotlin code, the return type of this method is given as Optional<Foo!>!. By using the @Nonnull annotation I can cut this down to Optional<Foo!> (i.e. only the Foo type is not null-checked anymore).

Is there a way to annotate the method to make the Kotlin compiler null-check the return value correctly?


Solution

  • You can do that by annotating the type use of Foo with some of the nullability annotations that the Kotlin compiler understands. Unfortunately, some annotation libraries from the list don't support type use annotation.

    I found that @NotNull from org.jetbrains:annotations:15.0 (but not 13.0) has the TYPE_USE target, so you can add the library as a dependency to your project and annotate the type use:

    import org.jetbrains.annotations.NotNull;
    
    ...
    
    public @NotNull Optional<@NotNull Foo> getFoo() {
        // always return some non-null value
    }
    

    Then the return type will be seen as Optional<Foo> in Kotlin.

    This, of course, can be done with any other nullability annotations from the list I mentioned above that support the TYPE_USE target.