2021年1月2日星期六

Why can't I use ! _displayCheckBox.value which is non-null MutableLiveData?

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

enter image description here

https://stackoverflow.com/questions/65546001/why-cant-i-use-displaycheckbox-value-which-is-non-null-mutablelivedata January 03, 2021 at 10:05AM

没有评论:

发表评论