Gradle在其API中提供了以下类:https://docs.gradle.org/5.6.4/javadoc/org/gradle/api/tasks/ScalaRuntime.html
此类具有一个接受Project
实例的简单构造函数。但是,在我的情况下,我手头没有Project
,但是我仍然想使用该类的其他方法,这些方法实际上并不依赖于此值,因此我决定将null
值传递给构造函数:
val scalaRuntime = ScalaRuntime(null)
但是,编译器失败,并出现以下错误:
Null can not be a value of a non-null type Project
我不确定这里会发生什么,因为显然这是Java类,而不是Kotlin,并且没有可空性注释。 Kotlin为何拒绝此密码?我假设它将期望类型为
Project!
(即平台类型)的值,而不是非空类型。现在解决此问题的唯一方法是使用反射来调用此构造函数,该构造函数自然可以很好地工作,因此,并不是像该构造函数期望一个真正不可为空的参数一样。
我在这里想念什么?为什么Kotlin假定构造函数参数为非null?
最佳答案
软件包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.
关于java - 纯Java API中的意外非空类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60069740/