Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 857
Bombe Avatar asked Sep 18 '26 08:09

Bombe


1 Answers

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.

like image 94
hotkey Avatar answered Sep 20 '26 13:09

hotkey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!