enum class ScreenState(val error: ErrorAlertType? = null) {
LOADING, ERROR, OK
}
enum class ErrorAlertType {
CONNECTION, UNKNOWN
}
and then
Copy code
val state = ScreenState.ERROR(ErrorAlertType.UNKNOWN)
How I can define my
ScreenState
to get optional parameter for
ERROR
state?
d
Damian Zawadzki
10/21/2021, 10:35 AM
Use sealed class instead:
Copy code
sealed class ScreenState {
object Loading : ScreenState()
data class Error(val error: ErrorAlertType? = null) : ScreenState()
object Ok : ScreenState()
}
enum class ErrorAlertType {
CONNECTION, UNKNOWN
}
val state = ScreenState.Error(ErrorAlertType.UNKNOWN)
➕ 1
g
Grégory Lureau
10/21/2021, 11:32 AM
Agree with Damian. Just to show the limitation, if you want to use enum there, you've to know there is only 1 instance of each entry in your enum, so you can define your enum like this :
Copy code
enum class ScreenState(val error: ErrorAlertType? = null) {
LOADING(ErrorAlertType.CONNECTION),
ERROR(ErrorAlertType.UNKNOWN),
OK
}
enum class ErrorAlertType {
CONNECTION, UNKNOWN
}
But it means you can't have LOADING(UNKNOWN) for example, or else you've to define 2 entries in ScreenState (LOADING_CONNECTION, LOADING_UNKNOWN.