在 Java 中为 Kotlin 编译器注释类型参数
Annotate Type Parameter in Java for Kotlin Compiler
在Java中,我有以下方法:
public Optional<Foo> getFoo() {
// always return some non-null value
}
在 Kotlin 代码中,此方法的 return 类型被指定为 Optional<Foo!>!
。通过使用 @Nonnull
注释,我可以将其缩减为 Optional<Foo!>
(即只有 Foo
类型不再进行空值检查)。
有没有办法注释使 Kotlin 编译器正确地对 return 值进行空检查的方法?
您可以通过注释 type use of Foo
with some of the nullability annotations that the Kotlin compiler understands 来做到这一点。不幸的是,列表中的某些注释库不支持类型使用注释。
我发现 org.jetbrains:annotations:15.0
中的 @NotNull
(但不是 13.0)具有 TYPE_USE
目标,因此您可以将库作为依赖项添加到项目中并注释类型使用:
import org.jetbrains.annotations.NotNull;
...
public @NotNull Optional<@NotNull Foo> getFoo() {
// always return some non-null value
}
那么 return 类型在 Kotlin 中将被视为 Optional<Foo>
。
当然,这可以通过我上面提到的列表中支持 TYPE_USE
目标的任何其他可空性注释来完成。
在Java中,我有以下方法:
public Optional<Foo> getFoo() {
// always return some non-null value
}
在 Kotlin 代码中,此方法的 return 类型被指定为 Optional<Foo!>!
。通过使用 @Nonnull
注释,我可以将其缩减为 Optional<Foo!>
(即只有 Foo
类型不再进行空值检查)。
有没有办法注释使 Kotlin 编译器正确地对 return 值进行空检查的方法?
您可以通过注释 type use of Foo
with some of the nullability annotations that the Kotlin compiler understands 来做到这一点。不幸的是,列表中的某些注释库不支持类型使用注释。
我发现 org.jetbrains:annotations:15.0
中的 @NotNull
(但不是 13.0)具有 TYPE_USE
目标,因此您可以将库作为依赖项添加到项目中并注释类型使用:
import org.jetbrains.annotations.NotNull;
...
public @NotNull Optional<@NotNull Foo> getFoo() {
// always return some non-null value
}
那么 return 类型在 Kotlin 中将被视为 Optional<Foo>
。
当然,这可以通过我上面提到的列表中支持 TYPE_USE
目标的任何其他可空性注释来完成。