Docs for Spring告诉我,myRepository.findOne(Id id)返回实体,如果没有find,则返回null,但IntelliJ说不同
我正在使用IntelliJ在Kotlin中进行编程实验。 我想检查我的实体findOne()返回是否存在通过检查是否为空,但IntelliJ显示警告:
条件’visitRankEntity!= null’总是’真’
我在这里错过了什么? 为什么IntelliJ显示警告?
@编辑
好的,当我加入时警告消失了?
VisitRankEntity
之后,所以行看起来像:
var visitRankEntity: VisitRankEntity? = visitRankRepository.findOne(WebfineryUtils.getDomainName(url))
既然我是Kotlin的新手,我忘了?
。 但是,如果该方法可以返回null,IntelliJ应该不会告诉我这个事实吗?
Kotlin和IntelliJ都不知道像findOne()
这样的java函数会返回null,除非它有一个@Nullable
或类似的注解。 当调用没有空值注解的java方法时,types既不是VisitRankEntity
也不是VisitRankEntity?
而是一个“平台types”,显示为VisitRankEntity!
。 它基本上是指“我不知道它是否可以空。
分配/投射VisitRankEntity!
由findOne()
返回VisitRankEntity?
是安全的,因为它更一般,不会产生警告。
分配/投射VisitRankEntity!
由findOne()
返回到VisitRankEntity
将产生一个编译器警告,说Declaration has type inferred from a platform call, which can lead to unchecked nullability issues. Specify type explicitly as nullable or non-nullable.
Declaration has type inferred from a platform call, which can lead to unchecked nullability issues. Specify type explicitly as nullable or non-nullable.
如果你碰巧知道findOne()
永远不会返回null,你可以通过改变findOne()!!
来消除这个警告findOne()!!
它基本上添加了一个非null断言,并将其转换为不可为空的VisitRankEntity
。
问题是Java中没有语法来表示可空性。 即使存在@Nullable
注释,值也可能为空,因为对它们没有一致意见(有@NonNull
, @Nullable
, @Nonnull
和其他一些变体), 并且没有强制执行 。
考虑下面的例子:
val queue: Queue = LinkedList() queue.peek().toInt()
在这种情况下,你使用peek,实际上可以返回null
但Kotlin编译器不会抱怨,所以如果你的Queue
是空的,你可以得到一个NullPointerException
。 这里的问题是我们使用了一个JDK接口Queue
,如果你看一下peek的实现:
/** * Retrieves, but does not remove, the head of this queue, * or returns {@code null} if this queue is empty. * * @return the head of this queue, or {@code null} if this queue is empty */ E peek();
它说peek
会返回E
,这会导致Kotlin相信E
不是空的,因为没有?
在声明( E?
)中也没有注释。 这可能会在Kotlin的未来版本中得到解决,但现在在项目中记住这一点非常重要,并使用这些接口:
val queue: Queue = LinkedList() queue.peek()?.toInt()
如果你有兴趣的话,我已经在这里广泛地写了这个。