[Question] Support sealed classes without requiring equals/hash?
See original GitHub issueI have a view that uses a sealed class ModelProp:
@ModelView(autoLayout = ModelView.Size.MATCH_WIDTH_WRAP_HEIGHT)
class QuestionCard(...) : FrameLayout(...) {
@ModelProp
fun setData(data: ObservableData<ProfileQuestion>) {
this.viewModel.data = data
}
}
Here’s the sealed class, for reference. It’s basically just to demonstrate the different states we could have:
sealed class ObservableData<out T> {
data class Data<out T>(val value: T) : ObservableData<T>()
object Empty : ObservableData<Nothing>()
data class Error<out T>(val throwable: Throwable?) : ObservableData<T>()
}
If I try to build my project like this, it fails because the model prop ObservableData<>
does not override hash code. I didn’t think I would need it since each class inside is its own data class or object, but maybe the compiler isn’t smart enough to notice. So in order for it to work, I had to override them even tho I could leave them empty:
sealed class ObservableData<out T> {
data class Data<out T>(val value: T) : ObservableData<T>()
object Empty : ObservableData<Nothing>()
data class Error<out T>(val throwable: Throwable?) : ObservableData<T>()
override fun equals(other: Any?): Boolean {
return super.equals(other)
}
override fun hashCode(): Int {
return super.hashCode()
}
}
I’m uncertain if anything needs to be changed about Epoxy here, but I wanted to verify that I do in fact have to override these methods, even if all they do is call through to super. If that’s the intended behavior of the library, I can at least make a note in my codebase if I chose to do it this way. I couldn’t find anything in searching the Epoxy repo though so I wanted to close the loop.
Issue Analytics
- State:
- Created 4 years ago
- Comments:6 (5 by maintainers)
@elihart Actually
@IgnoreRequireHashCode
is not an optimal solution IMO, it feels more like workaround and relies on discipline to not forget to check that all classes inheriting from this sealed class have proper implementation ofequals/hashCode
.The optimal solution would be to explicitly specify this contract in sealed class and let the compiler catch errors. This could be done in the following way:
I think that this would be better as an official advice in the wiki rather than
@IgnoreRequireHashCode
which could lead to broken behavior (diffing?) in some cases.Yes, that’s the whole point of it and the difference with DoNotHash