Code B works well, but the Code A get the following warning prompt (It can run), why?
Enum argument can be null in Java, but exhaustive when contains no null branch
I think _playState.value
can be null in Code B too, do I should add null branch when I use exhaustive when
in Code B?
Code A
private val _selectAction = MutableLiveData<ESelect>()
val selectAction: LiveData<ESelect> = _selectAction
selectAction.observe(mLifecycleOwner) {
when(it) { //Enum argument can be null in Java, but exhaustive when contains no null branch
ESelect.SelectAll -> binding.chSelect.isChecked = true
ESelect.UnselectAll -> binding.chSelect.isChecked = false
ESelect.NoAction -> Unit
}
}
enum class ESelect{
SelectAll,
UnselectAll,
NoAction
}
Code B
private val _playState=MutableLiveData<EPlayState>()
override fun playOrPause(filename: String) {
when (_playState.value) {
EPlayState.STOPPED -> play(filename)
EPlayState.PLAYING -> pause()
EPlayState.PAUSED -> resume()
}
}
enum class EPlayState {
STOPPED,
PLAYING,
PAUSED
}
Java allows any reference to be null, and references to enums aren't so special that a special case needs to be made to prevent it, or to provide another version of behaviour that is already well-specified and well-understood. Null is already a perfectly adequate sentinel value: we don't need another one.
In Java (from 1.5), enums are represented using enum data type. Java enums are more powerful than C/C++ enums. In Java, we can also add variables, methods and constructors to it. The main objective of enum is to define our own data types (Enumerated Data Types).
2. Reference Variable value: Any reference variable in Java has a default value null . 3. Type of null: Unlike the common misconception, null is not Object or neither a type. It’s just a special value, which can be assigned to any reference type and you can type cast null to any type Examples:
A common way of avoiding the NullPointerException is to check for null: In the real world, programmers find it hard to identify which objects can be null. An aggressively safe strategy could be to check null for every object. However, this causes a lot of redundant null checks and makes our code less readable.
LiveData
is written in Java
. The second parameter that you pass to the observe()
function is an anonymous implementation of Java interface Observer
. Since Java doesn't know anything about nullability in Kotlin, the parameter it
assumed to be nullable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With