Chills
03/19/2020, 12:39 PMEmil Kantis
03/19/2020, 12:41 PMEmil Kantis
03/19/2020, 12:42 PMdata class Response(val header: Header, val body: Body?, val error: Error?)
should be good enough?Chills
03/19/2020, 12:44 PMEmil Kantis
03/19/2020, 12:47 PMChills
03/19/2020, 12:47 PMChills
03/19/2020, 12:48 PMChills
03/19/2020, 1:04 PMMike
03/19/2020, 1:20 PMdiesieben07
03/19/2020, 1:32 PMNothing
type:
sealed class Response<out T> {
data class Value<T>(val v: T) : Response<T>()
data class Error(val err: Throwable) : Response<Nothing>()
}
Chills
03/19/2020, 1:34 PMChills
03/19/2020, 1:34 PMdiesieben07
03/19/2020, 1:35 PMChills
03/19/2020, 1:35 PMChills
03/19/2020, 1:36 PMdiesieben07
03/19/2020, 1:36 PMChills
03/19/2020, 1:38 PMChills
03/19/2020, 1:39 PMChills
03/19/2020, 1:39 PMdiesieben07
03/19/2020, 1:40 PMsealed class Message {
data class Header(val headerValue: String): Message()
data class Body(val bodyValue: String): Message()
data class Error(val error: Throwable): Message()
}
diesieben07
03/19/2020, 1:41 PMList<Message>
to represent all your casesChills
03/19/2020, 1:42 PMdiesieben07
03/19/2020, 1:45 PMsealed class Message<out HT, out BT> {
data class Header<out HT>(val headerValue: HT): Message<HT, Nothing>()
data class Body<out BT>(val bodyValue: BT): Message<Nothing, BT>()
data class Error(val error: Throwable): Message<Nothing, Nothing>()
}
fun main() {
val messages = listOf<Message<String, Int>>(
Message.Header("hello"),
Message.Body(15),
Message.Error(Exception("oops"))
)
for (message in messages) {
when (message) {
is Message.Header -> println("Header: ${message.headerValue}")
is Message.Body -> println("Body: ${message.bodyValue}")
is Message.Error -> println("error :(")
}
}
}
Chills
03/19/2020, 1:50 PMresponseSent:Array<Result<RsH,RsB>>
Result is a sealed class
as you see im mentioning the type RsH,RsB , so if something fails can't return Result<Nothing.Nothing>.Errordiesieben07
03/19/2020, 1:56 PMHT
and BT
are declared as out
. Because Nothing
is a subtype of everything, in that case Error
can substitute for any Message
, regardless of it's HT
and BT
.Chills
03/19/2020, 1:58 PMChills
03/19/2020, 1:59 PMChills
03/19/2020, 1:59 PMdiesieben07
03/19/2020, 2:00 PMwhen
example above, the compiler can check that you have covered all cases, if the class is sealed
.Chills
03/19/2020, 2:01 PMdiesieben07
03/19/2020, 2:01 PMChills
03/19/2020, 2:08 PMdiesieben07
03/19/2020, 2:18 PMdiesieben07
03/19/2020, 2:18 PMChills
03/19/2020, 2:18 PMMichael de Kaste
03/19/2020, 2:22 PMChills
03/19/2020, 2:27 PMChills
03/19/2020, 2:27 PMChills
03/19/2020, 2:28 PMChills
03/19/2020, 2:28 PMNothing
Chills
03/19/2020, 2:35 PMChills
03/19/2020, 2:36 PMChills
03/19/2020, 2:37 PM