在 Java 中为 Kotlin 编译器注释类型参数 [英] Annotate Type Parameter in Java for Kotlin Compiler

查看:29
本文介绍了在 Java 中为 Kotlin 编译器注释类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我有以下方法:

In Java, I have the following method:

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

在 Kotlin 代码中,此方法的返回类型为 Optional!.通过使用 @Nonnull 注释,我可以将其缩减为 Optional(即只有 Foo 类型不是空检查的不再).

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).

有没有办法对方法进行注释,让 Kotlin 编译器正确地对返回值进行空检查?

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

推荐答案

您可以通过注释 输入 Foo 和一些Kotlin 编译器理解的可空性注释.不幸的是,列表中的一些注解库不支持类型使用注解.

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.

我发现 @NotNull 来自 org.jetbrains:annotations:15.0(但不是 13.0)具有 TYPE_USE 目标,因此您可以将该库作为依赖项添加到您的项目并注释类型使用:

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
}

然后返回类型在 Kotlin 中将被视为 Optional.

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

当然,这可以使用我上面提到的支持 TYPE_USE 目标的列表中的任何其他可空性注释来完成.

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

这篇关于在 Java 中为 Kotlin 编译器注释类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆