这是我在Room.kt中的代码

@Query("SELECT * FROM databaseaugmentedskudetails WHERE sku = :sku")
fun getById(sku: String): DatabaseAugmentedSkuDetails
val result = getById(sku)
var canPurchase = if (result == null) true else result.canPurchase. // lint warns result == null is always false but in reality it can be null returned by dao

上面的行被翻译成Java
boolean canPurchase = result == null ? true : result.getCanPurchase();

一切正常,直到lint将我的kotlin代码更改为
var canPurchase = result?.canPurchase ?: true // lint warns safe call is unnecessary for non-null type

转换为Java代码如下
boolean canPurchase = result != null ? result.getCanPurchase() : null;

然后,我不时在运行时遇到以下崩溃
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference

我认为 Lint 应该足够聪明,不会破坏我的代码。

我的问题是

为什么将result?.canPurchase ?: true转换为result != null ? result.getCanPurchase() : null?不应该返回true而不是null吗?

最佳答案

函数声明必须使返回类型可为空,以便使Kotlin知道该函数最终可以返回可为空的类型。

@Query("SELECT * FROM databaseaugmentedskudetails WHERE sku = :sku")
fun getById(sku: String): DatabaseAugmentedSkuDetails? // <- ? here

08-18 16:52
查看更多