Code A works well, I think the _displayCheckBox.value
should be non-null, you can see Image A which is from the prompt of Android Studio.
I think I have initial the value of _displayCheckBox
using private val _displayCheckBox = MutableLiveData(false)
, so I think _displayCheckBox.value
will be non-null MutableLiveData.
But Code B cause the error "Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Boolean?", why?
Code A
private val _displayCheckBox = MutableLiveData(false)
val displayCheckBox : LiveData<Boolean> = _displayCheckBox
//Switch CheckBox On or Off
fun switchCheckBoxShowStatus(){
_displayCheckBox.value?.let {
_displayCheckBox.value = !it
}
}
Code B
private val _displayCheckBox = MutableLiveData(false)
val displayCheckBox : LiveData<Boolean> = _displayCheckBox
//Switch CheckBox On or Off
fun switchCheckBoxShowStatus(){
_displayCheckBox.value = ! _displayCheckBox.value // It cause error.
}
Image A
Added Content
I will always get "The value is false" for Code C.
So I think _aa.value will be non-null when I use val _aa = MutableLiveData(false)
, right?
Code C
val _aa = MutableLiveData(false)
Log.e("My","The value is "+_aa.value?:"null ")
@Nullable T
because thevalue
actually can be null even if the type is not nullable, where null indicates that no value has been set yet. A return type ofBoolean!
would not show an error if you treated it as non-nullable. – Tenfour04