问题描述
在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?
推荐答案
您可以通过注释类型使用(与.不幸的是,列表中的某些注释库不支持类型使用注释.
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编译器的注释类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!