The Code A is from the official sample project.
Result<out R> is a sealed class, I'm very strange why Loading is defined as object class.
I think the Code B is more reasonable, is it right?
Code A
sealed class Result<out R> {
data class Success<out T>(val data: T) : Result<T>()
data class Error(val exception: Exception) : Result<Nothing>()
object Loading : Result<Nothing>()
override fun toString(): String {
return when (this) {
is Success<*> -> "Success[data=$data]"
is Error -> "Error[exception=$exception]"
Loading -> "Loading"
}
}
}
Code B
sealed class Result<out R> {
data class Success<out T>(val data: T) : Result<T>()
data class Error(val exception: Exception) : Result<Nothing>()
data class Loading : Result<Nothing>()
override fun toString(): String {
return when (this) {
is Success<*> -> "Success[data=$data]"
is Error -> "Error[exception=$exception]"
is Loading -> "Loading"
}
}
}
Added Content:
To Tenfour04 and a_local_nobody: Thanks!
The Android Studio can compile and run after I add is before Loading -> "Loading" in Code C.
1: What are differents between Code A and Code C?
2: And more, In my mind, all types whithin sealed class should be the same, maybe they are all data class, or they are all object.
But Code A mix data class and object, and it's Ok, does it mean that I add even Interface whithin sealed class ?
Code C
sealed class Result<out R> {
data class Success<out T>(val data: T) : Result<T>()
data class Error(val exception: Exception) : Result<Nothing>()
object Loading : Result<Nothing>()
override fun toString(): String {
return when (this) {
is Success<*> -> "Success[data=$data]"
is Error -> "Error[exception=$exception]"
is Loading -> "Loading" // I add "is"
}
}
}