Jason5lee
03/15/2022, 10:21 AMsealed class QueryResult {
data class Success(...) : QueryResult()
object NotFound : QueryResult()
object SomeOtherError : QueryResult()
}
// API Code
when(result) {
is QueryResult.Success -> HttpResponse(200, "...")
QueryResult.NotFound -> HttpResponse(404, ...)
...
}
2.
sealed class QueryResult {
data class Success(...) : QueryResult()
data class Error(val status: HttpStatus, ...) : QueryResult()
}
// API Code
when (result) {
is QueryResult.Success -> HttpResponse(200, ...)
is QueryResult.Error -> HttpResponse(result.status, ...)
}
The second way is more convenient but the Error
type is coupled with the HTTP protocol.ephemient
03/15/2022, 10:29 AMsealed class QueryResult {
data class Success(...) : QueryResult()
sealed class Failure : QueryResult() {
object NotFound : Failure()
Rob Elliot
03/15/2022, 10:31 AMfun QueryResult.status(): HttpStatus = when (this) {
is QueryResult.Success -> OK
is QueryResult.NotFound -> NOT_FOUND
is QueryResult.SomeOtherError -> SERVER_ERROR
}
I like extension functions for translations between concerns, where neither should know about the other.