改善皮棉后使可运行时崩溃

问题描述 投票:1回答:1

这是我在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

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

我的问题是,

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

android kotlin android-room
1个回答
1
投票

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

@Query("SELECT * FROM databaseaugmentedskudetails WHERE sku = :sku")
fun getById(sku: String): DatabaseAugmentedSkuDetails? // <- ? here
© www.soinside.com 2019 - 2024. All rights reserved.