繁体   English   中英

可空变量在 get() 上抛出 NullPointerException

[英]Nullable variable throws NullPointerException on get()

这是一些错误。 我有这样一段代码:

if (countryCode.value.code != US_CODE){
      doSomething()
}

“如果”行抛出错误:NullPointerException:尝试在 null object 引用上调用虚拟方法“java.lang.String com.data.models.CountryCodeValue.getCode()”

“代码”字段可以为空,我不明白为什么会这样

国家代码值 model:

data class CountryCodeValue(
    val code: String? = null,
    val name: String,
    var description: String
)

看看你的错误行在说什么:

Error: NullPointerException: Attempt to invoke virtual method
'java.lang.String com.data.models.CountryCodeValue.getCode()' on a null object reference

它是说您正在尝试在 null 上调用getCode() ,而不是实际的CountryCodeValue null没有该方法,因此它会抛出。

您需要使用 null 安全检查来处理可能为空的内容:

// gives you the property if thing is non-null, otherwise you get null
thing?.property 

你可以将它们链接在一起:

// if any of these nullables are null, you get null instead of otherProperty
thing?.property?.otherProperty

LiveDatavalue可以是 null(例如,当它们为空时 - 我假设这就是你在这里使用的,但这适用于任何它)所以你必须 null 在你尝试访问之前检查你得到了什么它

if (countryCode.value?.code != US_CODE){
      doSomething()
}

请记住,这也可以返回 null(这就是你的全部问题!)所以你可能想在你的逻辑中处理它

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM