纯 Java API 中的意外非空类型
Unexpected non-null type in pure Java API
Gradle 在其 API 中提供以下 class:https://docs.gradle.org/5.6.4/javadoc/org/gradle/api/tasks/ScalaRuntime.html
这个 class 有一个简单的构造函数,它接受一个 Project
实例。然而,在我的例子中,我手头没有 Project
,但我仍然想使用这个 class 的其他方法,这些方法并不真正依赖于这个值,所以我决定传递一个null
给构造函数的值:
val scalaRuntime = ScalaRuntime(null)
但是,编译器失败并出现以下错误:
Null can not be a value of a non-null type Project
我不确定这里发生了什么,因为显然这是 Java class,而不是 Kotlin,并且没有可空性注释。为什么 Kotlin 会拒绝这段代码?我假设它期望 Project!
类型的值(即平台类型),而不是不可为 null 的类型。
现在解决此问题的唯一方法是使用反射来调用此构造函数,这自然可以很好地工作,因此此构造函数并不需要一个真正不可为 null 的参数。
我在这里错过了什么?为什么 Kotlin 假定构造函数参数是非空的?
包裹org.gradle.api.tasks
is annotated with @org.gradle.api.NonNullApi
:
Marks a type or a whole package as providing a non-null API by default. All parameter and return types are assumed to be Nonnull unless specifically marked as Nullable. All types of an annotated package inherit the package rule. Subpackages do not inherit nullability rules and must be annotated.
Gradle 在其 API 中提供以下 class:https://docs.gradle.org/5.6.4/javadoc/org/gradle/api/tasks/ScalaRuntime.html
这个 class 有一个简单的构造函数,它接受一个 Project
实例。然而,在我的例子中,我手头没有 Project
,但我仍然想使用这个 class 的其他方法,这些方法并不真正依赖于这个值,所以我决定传递一个null
给构造函数的值:
val scalaRuntime = ScalaRuntime(null)
但是,编译器失败并出现以下错误:
Null can not be a value of a non-null type Project
我不确定这里发生了什么,因为显然这是 Java class,而不是 Kotlin,并且没有可空性注释。为什么 Kotlin 会拒绝这段代码?我假设它期望 Project!
类型的值(即平台类型),而不是不可为 null 的类型。
现在解决此问题的唯一方法是使用反射来调用此构造函数,这自然可以很好地工作,因此此构造函数并不需要一个真正不可为 null 的参数。
我在这里错过了什么?为什么 Kotlin 假定构造函数参数是非空的?
包裹org.gradle.api.tasks
is annotated with @org.gradle.api.NonNullApi
:
Marks a type or a whole package as providing a non-null API by default. All parameter and return types are assumed to be Nonnull unless specifically marked as Nullable. All types of an annotated package inherit the package rule. Subpackages do not inherit nullability rules and must be annotated.