当从 Kotlin 调用非可空性注释的 Java 函数时,我们会得到灵活类型的返回值,用感叹号表示,例如String!
.
Kotlin 默默地允许将这些灵活的值分配给普通的非空类型,例如String
,这可能会在运行时导致 NullPointerExceptions。
我希望获得此类分配的编译器警告或错误。或者,将平台类型视为等同于可空类型(例如String?
)。
例如,使用此 Java 代码:
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
public class NullTest {
private String maybe() {
if (SystemClock.elapsedRealtimeNanos() % 2 == 0) {
return null;
}
return "ok";
}
public String annotatedNothing() { return maybe(); }
@Nullable public String annotatedNullable() { return maybe(); }
@NonNull public String annotatedNonNull() { return "ok"; }
}
...和下面的 Kotlin 代码,我想在两个新行上得到错误(见评论):
fun testnulls() {
val obj = NullTest()
val nullExact: String = obj.annotatedNullable() // already gives an error
val nullMaybe: String? = obj.annotatedNullable()
val nullInfer = obj.annotatedNullable()
val okayExact: String = obj.annotatedNonNull()
val okayMaybe: String? = obj.annotatedNonNull()
val okayInfer = obj.annotatedNonNull()
val bareExact: String = obj.annotatedNothing() // I want a compiler error here
val bareMaybe: String? = obj.annotatedNothing()
val bareInfer = obj.annotatedNothing()
print("length " + nullExact.length)
print("length " + nullMaybe.length) // already gives an error
print("length " + nullInfer.length) // already gives an error
print("length " + okayExact.length)
print("length " + okayMaybe.length) // already gives an error
print("length " + okayInfer.length)
print("length " + bareExact.length)
print("length " + bareMaybe.length) // already gives an error
print("length " + bareInfer.length) // I want a compiler error here
}
关键是这将迫使我添加空检查或!!
,确保我至少必须明确说明。
这可能吗?
在这篇2014 JetBrains 博客文章的评论中,当他们引入平台/灵活类型时,听起来他们正计划添加一个选项来警告这些情况,但我无法找到任何进一步的信息。