Stylianos Gakis
08/18/2023, 1:10 PMinternal sealed interface SomeUiState {
data class Success(val isReloading: Boolean = false): SomeUiState
data object Error : SomeUiState
}
And I want to add a convenience val isReloading: Boolean
to the interface itself to not have to check if it is Success first before actually checking the isReloading property, so avoid having to each time do (uiState is Success).isReloading
but be able to just call uiState.isReloading
What I initially thought I could do was this
internal sealed interface SomeUiState {
val isReloading: Boolean
get() = return this is Success && isReloading
data class Success(override val isReloading: Boolean = false): SomeUiState
data object Error : SomeUiState
}
But I can’t really do that since then this.isReloading
refers back to itself, doing an infinite recursive call.
What I can do instead is
val isReloading: Boolean
get() = this is Success && (this as Success).isReloading
But now I am doing a cast to Success which the IDE warns me is redundant, but if I do apply the quick fix I break my code.
So the question is, am I missing some better approach on how I can write this instead?Stylianos Gakis
08/18/2023, 1:11 PMinternal val HomeUiState.isReloading: Boolean
get() = this is HomeUiState.Success && this.isReloading
Which I feel like is my best bet here.bram
08/18/2023, 1:13 PMinternal val HomeUiState.isReloading = this is HomeUiState.Success && this.isReloading
Would this code be equivalent?Adam S
08/18/2023, 1:14 PMisReloading
to the interface and implement it in Error
internal sealed interface SomeUiState {
val isReloading: Boolean
data class Success(
override val isReloading: Boolean = false
): SomeUiState
data object Error : SomeUiState {
override val isReloading: Boolean
get() = false
}
}
Stylianos Gakis
08/18/2023, 1:15 PMAdam S
08/18/2023, 1:16 PMinternal sealed interface SomeUiState {
val isReloading: Boolean
get() = false
data class Success(
override val isReloading: Boolean = false
): SomeUiState
data object Error : SomeUiState
}
Stylianos Gakis
08/18/2023, 1:16 PMbram
08/18/2023, 1:17 PMStylianos Gakis
08/18/2023, 1:17 PMStylianos Gakis
08/18/2023, 1:18 PMKlitos Kyriacou
08/18/2023, 2:15 PMget() = this is Success && isReloading
It's not a recursive call at all. It's a virtual method call. The only problem is that IDEA gives you a false warning.Klitos Kyriacou
08/18/2023, 2:17 PMget() = (this as? Success)?.isReloading == true
Stylianos Gakis
08/18/2023, 2:19 PMget() = false
feels much cleaner than (this as? Success)?.isReloading == true
since I’d need to write overrides
anyway, so I don’t see this being a better option, having to do an extra cast there and all.