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

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

问题描述

在Java中,我有以下方法:

In Java, I have the following method:

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

在Kotlin代码中,此方法的返回类型为Optional<Foo!>!.通过使用@Nonnull批注,我可以将其缩减为Optional<Foo!>(即,不再对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?

推荐答案

您可以通过注释类型使用(与 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<Foo>.

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 for Kotlin编译器的注释类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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