这是我遇到过的最奇怪的问题。
所以 kotlin 和数据绑定(bind)再次让我陷入困境。我用代码开始我的问题。
模型类
data class ModelBottomItem(
@StringRes val name: Int,
@DrawableRes val image: Int,
val gender: Int = 0,
val enabled: Boolean = true,
val disabledIconColor: Int = 0)
: BaseModel()
布局代码
<variable
name="item"
type="myModel"/>
<TextView
android:text="@{item.gender == 0 ? @string/male : @string/female}"
...
/>
调试跟踪列表
0 = {ModelBottomItem@6406} "ModelBottomItem(name=2131755043, image=2131230862, gender=0, enabled=true, disabledIconColor=0)"
08-10 12:57:12.388 24902-24902/acr.browser.barebones E/AndroidRuntime: FATAL EXCEPTION: main Process: acr.browser.barebones, PID: 24902 java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
blah, blah !!
如果我改变item.gender == null
然后代码无法构建。它失败并出现以下错误。
error: incomparable types: int and <null> itemGenderJavaLangObjectNull = (itemGender) == (null);
用两行代码理解问题。
- 当我检查
item.gender == null
时 显示错误incomparable types: int and <null>
. - 当我检查
item.gender == 0
时,那么代码将会崩溃并显示int java.lang.Integer.intValue()' on a null object reference
如果运行时为 0。即使你可以看到调试跟踪,我的模型项是0,它不是**null**
。即使我已经将默认值设置为性别,即val gender: Int = 0
。 那怎么可能是null或者0呢?
最佳答案
对于这种情况,请像这样使用toIntOrNull()
item.gender.toString().toIntOrNull()
示例
val numb=""
val numb2="7"
val print1=numb.toIntOrNull()
println(print1) //out put is null
val print2=numb2.toIntOrNull()
println(print2) // output is 7
你的数据模型使用 nullable Int?
gender: Int? = 0 as parameter
像这样
data class ModelBottomItem(
@StringRes val name: Int,
@DrawableRes val image: Int,
val gender: Int?= 0,
val enabled: Boolean = true,
val disabledIconColor: Int = 0)
: BaseModel()
关于java - Kotlin 和数据绑定(bind) Int 值 null 检查问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51781455/