sealed class Resource<T>(val data: T? = null, val message: String? = null) {
class Success<T>(data: T) : Resource<T>(data)
class Loading<T>(data: T? = null) : Resource<T>(data)
class Error<T>(message: String, data: T? = null) : Resource<T>(message, data)
}
sealed class HttpError(val code: Int) {
object Unauthorized : HttpError(401)
object NotFound : HttpError(404)
}
enum class HttpErrorEnum(val code: Int) {
Unauthorized(401),
NotFound(404)
}
sealed class HttpError(val code: Int) {
data class Unauthorized(val reason: String) : HttpError(401)
object NotFound : HttpError(404)
}
enum class HttpErrorEnum(val code: Int) {
Unauthorized(401),
NotFound(404)
}
selaed class 의 경우 code 가 401 인 경우에만 reason 이라는 변수를 추가 생성하여 핸들링하려고 할 때 위의 소스코드 처럼 data class 로 정의하면 가능하다.
하지만, enum class 의 경우 위의 작업이 불가능하다.
// MainActivity.kt
val error: HttpErrorEnum = HttpErrorEnum.NotFound
HttpErrorEnum.value().forEach {::println}
when (error) {
is HttpErrorEnum.Unauthorized -> Unit
is HttpErrorEnum.NotFound -> Unit
}
sealed class HttpError(val code: Int) {
data class Unauthorized(val reason: String) : HttpError(401)
object NotFound : HttpError(404)
}
sealed interface HttpError {
data class Unauthorized(val reason: String) : HttpError
object NotFound : HttpError
}